题面
题解(Flood Fill 模型)
本题是八联通形式,我们直接枚举每一个格子,如果有水并且是没有被标记过的,那么就开始做Flood Fill ,将所有联通的水源标记,联通的数量+1,
代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
int n, m;
char g[N][N];
PII q[N * N];
bool st[N][N];
void bfs(int sx, int sy) {
st[sx][sy] = true;
int hh = 0, tt = -1;
q[++tt] = {sx, sy};
while (hh <= tt) {
auto t = q[hh++];
int x = t.first, y = t.second;
//枚举8联通,中间的忽略
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (i == x && j == y) continue;
if (i < 0 || i > n - 1 || j < 0 || j > m - 1) continue;
if (g[i][j] == '.' || st[i][j]) continue;
q[++tt] = {i, j};
st[i][j] = true;
}
}
}
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> g[i][j];
}
}
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == 'W' && !st[i][j]) {
bfs(i, j);
res++;
}
}
}
cout << res << endl;
return 0;
}