本质上来讲Flood Fill算法就是从一个点开始往外发散,将联通的位置覆盖为一整个部分,最常用的实现方法是BFS,当然DFS也是可以实现的。这类题在代码上是极其相似的,有着固定的套路,只不过在一些细节上需要处理一下。
池塘计数
using namespace std; const int N = 1007, M = N * N;
define x first
define y second
typedef pair
int n, m, cnt; char g[N][N]; // 地图
int dx[8] = {-1, 1, -1, 1, 0, 0, 1, -1}; int dy[8] = {-1, 1, 1, -1, -1, 1, 0, 0};
void bfs(int sx, int sy) {
queue
int main() {
scanf("%d%d", &n, &m);for (int i = 0; i < n; ++i) scanf("%s", g[i]);for (int i = 0; i < n; ++i) {for (int j = 0; j < m; ++j) {if (g[i][j] == 'W') {bfs(i, j);cnt++;}}}printf("%d\n", cnt);return 0;
}
---<a name="jyqvF"></a># [城堡问题](https://www.acwing.com/problem/content/1100/)- 求二维城堡中有多少个房间- 需要判断四个方向- 用位运算来判墙,相比上一题,在判断上要稍微复杂一点```cpp# include<iostream># include<algorithm># include<queue>using namespace std;# define x first# define y secondtypedef pair<int, int> PII;const int N = 55;int n, m;int g[N][N];bool st[N][N];queue<PII> q;int dx[4] = {0, -1, 0, 1}; // 左上右下,与墙的位对应int dy[4] = {-1, 0, 1, 0};int bfs(int sx, int sy) {int area = 0;q.push({sx, sy});st[sx][sy] = true;while (!q.empty()) {PII t = q.front(); q.pop();area++;for (int i = 0; i < 4; ++i) {int xx = t.x + dx[i], yy = t.y + dy[i];if (xx < 0 || xx >= n || yy < 0 || yy >= m || st[xx][yy]) continue;if (g[t.x][t.y] >> i & 1) continue; // 有墙q.push({xx, yy});st[xx][yy] = true;}}return area;}int main() {cin >> n >> m;for (int i = 0; i < n; ++i) {for (int j = 0; j < m; ++j) {cin >> g[i][j];}}int cnt = 0, area = 0;for (int i = 0; i < n; ++i) {for (int j = 0; j < m; ++j) {if (!st[i][j]) {area = max(area, bfs(i, j));cnt++;}}}cout << cnt << endl;cout << area;return 0;}
山峰和山谷
using namespace std;
define x first
define y second
typedef pair
const int N = 1010;
int n;
int h[N][N];
queue
int dx[8] = {-1, 0, 1, 0, -1, -1, 1, 1}; int dy[8] = {0, -1, 0, 1, -1, 1, 1, -1};
void bfs(int sx, int sy, bool& has_higher, bool& has_lower) { q.push({sx, sy}); st[sx][sy] = true;
while (!q.empty()) {PII t = q.front(); q.pop();for (int i = 0; i < 8; ++i) {int xx = t.x + dx[i], yy = t.y + dy[i];if (xx < 0 || xx >= n || yy < 0 || yy >= n) continue;if (h[xx][yy] != h[t.x][t.y]) { // 想称为山峰或山谷必须得是一样高的,如不同则不为谋if (h[xx][yy] > h[t.x][t.y]) has_higher = true; // 当前位置不是山峰else has_lower = true; // 不是山谷} else if (!st[xx][yy]) {q.push({xx, yy});st[xx][yy] = true;}}}
}
int main() {
cin >> n;for (int i = 0; i < n; ++i) {for (int j = 0; j < n; ++j) {cin >> h[i][j];}}int peak = 0, valley = 0; // 山峰与山谷的个数for (int i = 0; i < n; ++i) {for (int j = 0; j < n; ++j) {if (!st[i][j]) {bool has_higher = false, has_lower = false;bfs(i, j, has_higher, has_lower);if (!has_higher) peak++; // 一堆既可能是山峰也可能同时是山谷if (!has_lower) valley++;}}}cout << peak << ' ' << valley;return 0;
} ```
