Files
python/TangDou/AcWing/FloodFill/1097_dfs.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

35 lines
946 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, m, ans;
char g[N][N];
// 方向数组
int dx[] = {1, 0, -1, 0, 1, -1, 1, -1};
int dy[] = {0, 1, 0, -1, 1, -1, -1, 1};
void dfs(int x, int y) {
g[x][y] = '.'; // 这样可以不用使用st数组,妙!
for (int i = 0; i < 8; i++) {
int tx = x + dx[i], ty = y + dy[i];
if (g[tx][ty] == 'W') dfs(tx, ty);
}
}
int main() {
cin >> n >> m;
// 使有深度优先搜索时,注意下标从1开始,这样相当于构建了一个四周为0的墙,不会越界
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> g[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (g[i][j] == 'W') { // 找到“ W ”.
dfs(i, j);
ans++; // 统计答案
}
printf("%d\n", ans);
return 0;
}