爆搜,能到的就标记输出原数字,到不了的输出2
#include <bits/stdc++.h>
using namespace std;\
int z[35][35];
int n;
bool vis[35][35];
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
void dfs(int fx, int fy){
if (vis[fx][fy] == 1){
return;
}
vis[fx][fy] = 1;
for (int i = 0; i < 4; i++){
int xx = fx + dx[i], yy = dy[i] + fy;
if (xx >= 1 && xx <= n && yy >= 1 && yy <= n && !vis[xx][yy]){
dfs(xx, yy);
}
}
}
int main () {
ios::sync_with_stdio(false);
cin.tie(0);//关闭流同步
cin >> n;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
cin >> z[i][j];
if (z[i][j] == 1){
vis[i][j] = 1;
}
}
}
for (int i = 1, j = 1; j <= n; j++){
dfs(i,j);
}
for (int i = n, j = 1; j <= n; j++){
dfs(i,j);
}
for (int i = 2, j = 1; i < n; i++){
dfs(i,j);
}
for (int i = 2, j = n; i < n; i++){
dfs(i,j);
}
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
if (z[i][j] == 0 && !vis[i][j]){
cout << 2 << ' ';
}
else{
cout << z[i][j] << ' ';
}
}
cout << '\n';
}
return 0;
}