题解
2025-08-20 10:59:10
发布于:四川
1阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
int n;
int grid[50][50];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
void bfs() {
queue<pair<int, int>> q;
for (int i = 0; i <= n + 1; i++) {
for (int j = 0; j <= n + 1; j++) {
if ((i == 0 || i == n + 1 || j == 0 || j == n + 1) && grid[i][j] == 0) {
grid[i][j] = -1;
q.push({i, j});
}
}
}
while (!q.empty()) {
auto [x, y] = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx <= n + 1 && ny >= 0 && ny <= n + 1 && grid[nx][ny] == 0) {
grid[nx][ny] = -1;
q.push({nx, ny});
}
}
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> grid[i][j];
}
}
bfs();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (grid[i][j] == -1) cout << 0 << " ";
else if (grid[i][j] == 0) cout << 2 << " ";
else cout << 1 << " ";
}
cout << endl;
}
return 0;
}
这里空空如也
有帮助,赞一个