pocaogaozhi @ 2023-07-15 16:00:31
#include <bits/stdc++.h>
using namespace std;
int n;
int a[40][40];
int b[40][40];
int xf[4] = {1, -1, 0, 0};
int yf[4] = {0, 0, -1, 1};
void dfs(int x, int y) {
if (x >= 1 && x <= n && y >= 1 && y >= n && b[x][y] == 0) {
b[x][y] = 1;
for (int i = 0; i < 4; i++) {
if (a[x + xf[i]][y + yf[i]] == 0) {
dfs(x + xf[i], y + yf[i]);
}
}
}
}
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];
}
}
dfs(1, 1);
dfs(1, n);
dfs(n, 1);
dfs(n, n);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (b[i][j] == 0) a[i][j] = 2;
cout << a[i][j] << " ";
}
cout << endl;
}
}
by collin @ 2023-07-24 15:23:34
你这样会有一个bug,就是如果1,1是个1的情况就行不通了,建议你把它看成是一个0,0到n+1,n+1的数组,从0,0开始遍历,这样角上也能遍历到,也可以避免上述情况
by NO_OI_NO_LIFE @ 2023-07-24 17:20:15
y<=n