DFS:
经典模板题,按照模板来即可
class Solution {
public:
int tx,ty,n,m,count=0,nextt[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int maxAreaOfIsland(vector<vector<int>>& grid) {
n=grid.size();m=grid[0].size();
int grid_max=-1,sign=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j]==1)
{
sign=1;
count=0;
grid_max=max(grid_max,dfs(grid,i,j));
}
}
}
if(sign)
return grid_max;
else
return 0;
}
int dfs(vector<vector<int> >& grid,int x,int y)
{
if(grid[x][y]==1)
{
count++;
grid[x][y]=0;
for(int i=0;i<4;i++)
{
tx=x+nextt[i][0];
ty=y+nextt[i][1];
if(tx<0||ty<0||tx>=n||ty>=m||grid[tx][ty]==0)
continue;
dfs(grid,tx,ty);
}
}
return count;
}
};
BFS:
同样运用模板即可
class Solution {
public://BFS
int ans=-1;
int nextt[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int maxAreaOfIsland(vector<vector<int>>& grid) {
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[0].size();j++)
{
int cur=0;
if(grid[i][j]==1)
{
queue<pair<int,int> >neighters;
neighters.push({i,j});
while(!neighters.empty())
{
pair<int,int> ij=neighters.front();
neighters.pop();//这里注意判断上下左右是否会越界与判断是不是0
if(ij.first<0||ij.second<0||ij.first>=grid.size()||ij.second>=grid[0].size()||grid[ij.first][ij.second]==0)
continue;
grid[ij.first][ij.second]=0;
cur++;
for(int i=0;i<4;i++)
{
int next_i=ij.first+nextt[i][0];
int next_j=ij.second+nextt[i][1];
neighters.push({next_i,next_j});
}
}
}
ans=max(cur,ans);
}
}
return ans;
}
};