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.
题意:求面积最大的岛。给个二维数组,数组里只有0或者1,,0代表水,1代表陆地,垂直或者水平上的1可以算作是一个岛,斜对角不行,求面积最大的岛包含多少个1?
分析:深度优先搜索,可递归,也可以用栈实现非递归,当grid[i][j] 周围有超过两个及以上的1时,将该点入栈。
下面是递归的代码:
class Solution {
private: int cnt=0; //记录岛的面积
public:
void dfs(vector<vector<int>>& grid,int i,int j)
{
if(i<0||i>=grid.size()||j<0||j>=grid[0].size())
return ;
if(!grid[i][j])
{
return;
}
cnt++;
grid[i][j]=0; //标记成已经访问
dfs(grid,i-1,j); //
dfs(grid,i,j-1); //扫描四个方向
dfs(grid,i+1,j); //
dfs(grid,i,j+1); //
return;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
vector<int> b;
int m=grid.size();
int n=grid[0].size();
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(grid[i][j])
{
dfs(grid,i,j);
b.push_back(cnt);
cnt=0;
}
}
int max=0;
for(int i=0;i<b.size();i++)
if(max<=b[i])
max=b[i];
return max;
}
};