要求:找连起来的1
思路:dfs,不开visit,直接用原数组记录。也可以用bfs或者dfs+栈
class Solution {
public:
int dfs(vector<vector<int>>& grid,int x,int y,int &count,int m,int n){
if(grid[x][y]==1){
grid[x][y]=2;
++count;
int di[4]={0,0,1,-1};
int dj[4]={1,-1,0,0};
for(int i=0;i<4;++i)
if(x+di[i]>=0&&x+di[i]<=m-1&&y+dj[i]>=0&&y+dj[i]<=n-1)
if(grid[x+di[i]][y+dj[i]]==1)
dfs(grid,x+di[i],y+dj[i],count,m,n);
}
return count;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int m=grid.size(),n=grid[0].size();
int maxcount=0;
for(int x=0;x<m;++x){
for(int y=0;y<n;++y){
int count=0;
if(grid[x][y]==1)
maxcount=max(maxcount,dfs(grid,x,y,count,m,n));
}
}
return maxcount;
}
};