Flood Fill 解决连通块问题
算法思路博客: AcWing 1097. 池塘计数
AcWing 1097. 池塘计数
思路:bfs 寻找连通块数量
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e3+10;
int n, m;
char str[N][N];
bool vis[N][N];
int dx[] = {0, 0, 1, 1, 1, -1, -1, -1}, dy[] = {1, -1, 1, 0, -1, 1, 0, -1};
void bfs(int sx, int sy)
{
queue<pair<int, int> > que;
que.push({sx, sy});
vis[sx][sy] = 1;
while(!que.empty())
{
auto t = que.front(); que.pop();
int x = it.first, y = it.second;
for(int i=0; i<8; i++){
int xx = x + dx[i], yy = y + dy[i];
if(xx < 0 || xx >= n || yy < 0 || yy >= m || str[xx][yy] == '.' || vis[xx][yy]) continue;
vis[xx][yy] = 1;
que.push({xx, yy});
}
}
}
int main()
{
cin >> n >> m;
for(int i=0; i<n; i++) cin >> str[i];
int cnt = 0;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
if(str[i][j] == 'W' && vis[i][j] == 0) // 发现新大陆,开始拓荒(bfs)
{
bfs(i, j);
cnt ++;
}
cout << cnt;
system("pause");
return 0;
}