Given a non-empty 2D array grid
of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
class Solution {
public:
int areaNum(vector<vector<int>>& grid, int m ,int n){
if (m<grid.size()&&m>=0&&n<grid[0].size()&&n>=0&&grid[m][n]==1) {
//将经过的位置标记为0,避免循环检验
grid[m][n] = 0;
return 1+ areaNum(grid, m+1, n)+areaNum(grid, m, n+1)+areaNum(grid, m-1, n)+areaNum(grid, m, n-1);
}
return 0;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int result = 0;
for (int i =0; i<grid.size(); i++) {
for (int j=0; j<grid[0].size(); j++) {
if (grid[i][j]==1) {
result = max(result, areaNum(grid, i, j));
}
}
}
return result;
}
};