分析
- 对于某一个方向是否有墙的判断:可以用二进制判断,左上右下分别用0、1、2、3代表,则可以使用
g[x][y] >> i & 1
判断(这里的i就是刚才的0、1、2、3)。其他直接使用floodfill
算法求解即可。
BFS
// BFS
#include <iostream>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 55, M = N * N;
int n, m;
int g[N][N];
PII q[M];
bool st[N][N];
int bfs(int sx, int sy) {
int hh = 0, tt = 0;
int area = 0;
int dx[4] = {0, -1, 0, 1}, dy[4] = {-1, 0, 1, 0}; // 左上右下
q[0] = {sx, sy};
st[sx][sy] = true;
while (hh <= tt) {
auto t = q[hh++];
area++;
for (int i = 0; i < 4; i++) {
int a = t.x + dx[i], b = t.y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= m) continue;
if (st[a][b]) continue;
if (g[t.x][t.y] >> i & 1) continue;
q[++tt] = {a, b};
st[a][b] = true;
}
}
}
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 << endl;
return 0;
}
DFS
// DFS
#include <iostream>
#define x first
#define y second
using namespace std;
const int N = 55;
int n, m;
int g[N][N];
bool st[N][N];
int dx[] = {0, -1, 0, 1}, dy[] = {-1, 0, 1, 0}; // 上右下左
int dfs(int sx, int sy) {
st[sx][sy] = true;
int area = 1;
for (int i = 0; i < 4; i++) {
int a = sx + dx[i], b = sy + dy[i];
if (a >= 0 && a < n && b >= 0 && b < m && !(g[sx][sy] >> i & 1) && !st[a][b])
area += dfs(a, b);
}
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, dfs(i, j));
cnt++;
}
cout << cnt << endl;
cout << area << endl;
return 0;
}