给定一个包含了一些 0 和 1的非空二维数组 grid
, 一个 岛屿 是由四个方向 (水平或垂直) 的 1
(代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
示例 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]]
对于上面这个给定矩阵应返回 6
。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。
示例 2:
[[0,0,0,0,0,0,0,0]]
对于上面这个给定的矩阵, 返回 0
。
class Solution {
public:
bool vis[51][51] = {false};
int max = 0;
void dfs(vector<vector<int>>& grid,int x,int y,int& sum,int n,int m){
if(grid[x][y]==0||vis[x][y]==true)return;
++sum;
vis[x][y] = true;
if(x-1>=0)dfs(grid,x-1,y,sum,n,m);
if(x+1<n)dfs(grid,x+1,y,sum,n,m);
if(y-1>=0)dfs(grid,x,y-1,sum,n,m);
if(y+1<m)dfs(grid,x,y+1,sum,n,m);
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
int max = 0;
for(int i = 0;i<n;i++){
for(int j = 0;j<m;j++){
if(grid[i][j]==1&&vis[i][j]==false){
int sum = 0;
dfs(grid,i,j,sum,n,m);
if(max<=sum)max = sum;
}
}
}
return max;
}
};