LeetCode 695 Max Area of Island
题目分析
https://leetcode.com/problems/max-area-of-island/
深度优先搜索
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int res = 0;
for (int i=0; i<grid.size(); i++) {
for (int j=0; j<grid[0].size(); j++) {
if (grid[i][j] == 1) {
int cnt = 0;
travelIsland(i, j, grid, cnt);
res = max(res, cnt);
}
}
}
return res;
}
void travelIsland(int i, int j, vector<vector<int>>& grid, int& count) {
if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size()) return;
if (grid[i][j] == 1) {
grid[i][j] = 2; // mark as visited island
count += 1;
travelIsland(i+1, j, grid, count);
travelIsland(i-1, j, grid, count);
travelIsland(i, j+1, grid, count);
travelIsland(i, j-1, grid, count);
}
}
};