You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.7 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 40;
int n;
int a[N][N];
int b[N][N];
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
struct coord {
int x, y;
};
//广度优先搜索
void bfs(int x, int y) {
queue<coord> q;
q.push({x, y});
while (!q.empty()) {
coord p = q.front();
q.pop();
b[p.x][p.y] = -1;
for (int i = 0; i < 4; i++) {
int x1 = p.x + dx[i], y1 = p.y + dy[i];
if (b[x1][y1] >= 0 && x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= n && a[x1][y1] == 0) {
q.push({x1, y1});
b[x1][y1] = -1;
}
}
}
}
int main() {
//读入地图
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
cin >> a[i][j];
b[i][j] = a[i][j];
}
//思路从边缘四条外边找0然后BFS找出所有区域这些区域就是不被圈起来的范围进行标识再取反
for (int i = 1; i <= n; i++)
if (a[1][i] == 0) bfs(1, i); //第一行
for (int i = 1; i <= n; i++)
if (a[i][1] == 0) bfs(i, 1); //第一列
for (int i = 1; i <= n; i++)
if (a[n][i] == 0) bfs(n, i); //最后一行
for (int i = 1; i <= n; i++)
if (a[i][n] == 0) bfs(i, n); //最后一列
//输出
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (b[i][j] == -1) cout << 0 << " ";
else if (b[i][j] == 0) cout << 2 << " ";
else cout << b[i][j] << " ";
}
cout << endl;
}
return 0;
}