题目链接:https://leetcode.cn/problems/number-of-islands/
题目如下:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
//flood-fill算法,要遍历每一个格子,然后分别bfs or dfs
int res=0;
int m=grid.size();
if(m==0) return res;
int n=grid[0].size();
vector<vector<bool>> visited(m,vector<bool>(n,false));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(visited[i][j]==false&&grid[i][j]=='1'){
res++;
bfs(grid,i,j,visited,m,n);
}
}
}
return res;
}
void bfs(vector<vector<char>> g,int x,int y,vector<vector<bool>>& visited,int m,int n){
queue<pair<int,int>> que;
que.push({x,y});
visited[x][y]=true;
while(que.size()){
auto t=que.front();
que.pop();
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
for(int i=0;i<4;i++){
int a=t.first+dx[i];
int b=t.second+dy[i];
if(a>=0&&a<m&&b>=0&&b<n&&visited[a][b]==false&&g[a][b]=='1'){
que.push({a,b});
visited[a][b]=true;
}
}
}
}
};