题见洛谷
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
using namespace std;
int a[40][40],n;
bool f[40][40];
int dx[]={0,1,-1,0,0};int dy[]={0,0,0,1,-1};
struct que{
int x;
int y;
}pos[2000];
void bfs()
{
int head=0,tail=0;
for(int i=1;i<=n;i++){
if(a[1][i]==0&&!f[1][i]){
pos[++tail].x=1;pos[tail].y=i;f[1][i]=true;
}
if(a[i][1]==0&&!f[i][1]){
pos[++tail].x=i;pos[tail].y=1;f[i][1]=true;
}
if(a[n][i]==0&&!f[n][i]){
pos[++tail].x=n;pos[tail].y=i;f[n][i]=true;
}
if(a[i][n]==0&&!f[i][n]){
pos[++tail].x=i;pos[tail].y=n;f[i][n]=true;
}
while(head<tail){
head++;
for(int i=1;i<=4;i++){
int nx=pos[head].x+dx[i],ny=pos[head].y+dy[i];
if(nx<=n&&nx>=1&&ny>=1&&ny<=n)
if(!f[nx][ny]){
pos[++tail].x=nx;pos[tail].y=ny;f[nx][ny]=true;
}
}
}
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
scanf("%d",&a[i][j]);
if(a[i][j]==1)f[i][j]=true;
}
bfs();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)
if(!f[i][j])printf("2 ");
else printf("%d ",a[i][j]);
puts("");
}
return 0;
}