题目描述
由数字0组成的方阵中,有一任意形状闭合圈,闭合圈由数字1构成,围圈时只走上下左右4个方向。现要求把闭合圈内的所有空间都填写成2.例如:6×6的方阵(n=6),
涂色前和涂色后的方阵如下:
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1
输入格式
每组测试数据第一行一个整数n(1≤n≤30)
接下来n行,由0和1组成的n×n的方阵。
方阵内只有一个闭合圈,圈内至少有一个0。
输出格式
已经填好数字2的完整方阵。
输入输出样例
输入
6
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
输出
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1
说明/提示
1≤n≤30
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int,int>PII;
const int maxn = 35;
int dx[] = {-1,0,1,0}; //方向数组
int dy[] = {0,1,0,-1};
int g[maxn][maxn];
bool vis[maxn][maxn];
int n;
void bfs(int x,int y){
queue<PII>q;
q.push({x,y});
vis[x][y]=true;
while(q.size()){
PII t=q.front();
q.pop();
for(int j = 0;j < 4;j++) {
int a = t.x + dx[j];
int b = t.y + dy[j];
if(a < 0 || a > n + 1 || b < 0 || b > n + 1 || g[a][b]==1 || vis[a][b]) {
continue;
}
vis[a][b]=true;
q.push({a,b});
}
}
}
int main() {
cin >> n;
for(int i = 1;i <= n;i++) {
for(int j = 1;j <= n;j++) {
cin >> g[i][j];
}
}
bfs(0,0);//最外圈加一圈0
for(int i = 1;i <= n;i++) {
for(int j = 1;j <= n;j++) {
if(!vis[i][j]&&!g[i][j])cout<<2<<' ';
else cout<<g[i][j]<<' ';
}
cout<<endl;
}
return 0;
}