BFS
#include <iostream>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 1010, M = N * N;
int n, m;
char g[N][N]; // 存储地图
PII q[M];
bool st[N][N]; // 判重数组
void bfs(int sx, int sy) {
int hh = 0, tt = 0;
q[0] = {sx, sy};
st[sx][sy] = true;
while (hh <= tt) {
auto t = q[hh++];
for (int i = t.x - 1; i <= t.x + 1; i++)
for (int j = t.y - 1; j <= t.y + 1; j++) {
if (i == t.x && j == t.y) continue;
if (i < 0 || i >= n || j < 0 || j >= m) continue;
if (g[i][j] == '.' || st[i][j]) continue;
q[++tt] = {i, j};
st[i][j] = true;
}
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) scanf("%s", g[i]);
int cnt = 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);
cnt++;
}
printf("%d\n", cnt);
return 0;
}
DFS
// DFS
#include <iostream>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
int n, m;
char g[N][N]; // 存储地图
bool st[N][N]; // 判重数组
void dfs(int sx, int sy) {
st[sx][sy] = true;
for (int i = sx - 1; i <= sx + 1; i++)
for (int j = sy - 1; j <= sy + 1; j++) {
if (i >= 0 && i < n && j >= 0 && j < m && g[i][j] == 'W' && !st[i][j])
dfs(i, j);
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) scanf("%s", g[i]);
int cnt = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (g[i][j] == 'W' && !st[i][j]) {
dfs(i, j);
cnt++;
}
printf("%d\n", cnt);
return 0;
}