代码如下
#include<bits/stdc++.h>
using namespace std;
int n, m,ans;
char a[101][101];
queue<int>h;
queue<int>p;
inline void bfs(int x, int y) {
a[x][y] = '.';
int xx, yy;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
xx = x + i;
yy = y + j;
if (xx >= 0 && xx < n && yy >= 0 && yy < m && a[xx][yy] == 'W') {
h.push(xx);
p.push(yy);
}
}
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin>>a[i];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i][j] == 'W') {
h.push(i);
p.push(j);
while (!h.empty()) {
bfs(h.front(), p.front());
h.pop();
p.pop();
}
ans++;
}
}
}
cout << ans;
return 0;
}
![测试结果]()