原题链接:Leecode 200. 岛屿数量
DFS:
class Solution {
public:
void dfs(vector<vector<char>>& grid,int i,int j)
{
int m=grid.size(),n=grid[0].size();
grid[i][j]='2';
if(i && grid[i-1][j]=='1') dfs(grid,i-1,j);
if(i+1<m && grid[i+1][j]=='1') dfs(grid,i+1,j);
if(j && grid[i][j-1]=='1') dfs(grid,i,j-1);
if(j+1<n && grid[i][j+1]=='1') dfs(grid,i,j+1);
}
int numIslands(vector<vector<char>>& grid) {
int m=grid.size(),n=grid[0].size();
int res=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(grid[i][j]=='1')
{
res++;
dfs(grid,i,j);
}
}
}
return res;
}
};
BFS:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m=grid.size(),n=grid[0].size();
int res=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(grid[i][j]=='1')
{
queue<pair<int,int>> q;
q.push({i,j});
res++;
grid[i][j]='2';
while(!q.empty())
{
auto node=q.front();
q.pop();
int x=node.first,y=node.second;
if(x && grid[x-1][y]=='1')
{
q.push({x-1,y});
grid[x-1][y]='2';
}
if(x+1<m && grid[x+1][y]=='1')
{
q.push({x+1,y});
grid[x+1][y]='2';
}
if(y && grid[x][y-1]=='1')
{
q.push({x,y-1});
grid[x][y-1]='2';
}
if(y+1<n && grid[x][y+1]=='1')
{
q.push({x,y+1});
grid[x][y+1]='2';
}
}
}
}
}
return res;
}
};