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

43 lines
1.3 KiB
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 = 55;
int g[N][N];
int st[N][N];
int n, m, ans; //注意这里的ans不能做为dfs参数进行传递,因为维护的是同一个变量
int dx[] = {0, -1, 0, 1}; //左上右上
int dy[] = {-1, 0, 1, 0}; //西北东南 1 2 4 8 二进制位运算,参考1098_0.cpp
void dfs(int sx, int sy) {
st[sx][sy] = true; //标识此位置已访问过
ans++; //到达一个位置,那么面积肯定增大一个
for (int i = 0; i < 4; i++) {
int x = sx + dx[i], y = sy + dy[i];
if (x == 0 || x > n || y == 0 || y > m) continue;
if (st[x][y]) continue;
if (g[sx][sy] >> i & 1) continue; //自带数位压缩表示法~,有墙
dfs(x, y);
}
}
int cnt, area;
int main() {
cin >> n >> m;
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 (!st[i][j]) {
cnt++; //连通块数量
ans = 0; //清零重新统计
dfs(i, j); //开始Flood Fill
area = max(area, ans); // PK目前的最大面积
}
//输出结果
printf("%d\n%d\n", cnt, area);
return 0;
}