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.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6
. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0
.
Note: The length of each dimension in the given grid
does not exceed 50.
题目链接:https://leetcode-cn.com/problems/max-area-of-island/
思路
二维平面的递归。
这种题不需要改变状态,只要做统计的,就可以按顺序访问没有遇到的节点,在节点中向四周递归即可。
class Solution {
public:
int res = 0;
int maxAreaOfIsland(vector<vector<int>>& grid) {
int row = grid.size();
if(row==0) return 0;
int col = grid[0].size();
for(int i=0; i<row; ++i){
for(int j=0; j<col; ++j){
if(grid[i][j]==1){
res = max(res, trace(grid, i,j));
}
}
}
return res;
}
int trace(vector<vector<int>> &grid, int i, int j){
int row = grid.size(), col = grid[0].size();
if(i<0 || i>=row || j<0 || j>=col) return 0;
if(grid[i][j]==1){
grid[i][j] = 2;
return 1+trace(grid,i-1,j)+trace(grid,i,j-1)+trace(grid,i+1,j)+trace(grid,i,j+1);
}else if(grid[i][j]!=2){
grid[i][j] = -1;
}
return 0;
}
};