题目描述
由数字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
#include<iostream>
#include<queue>
using namespace std;
int n, map[32][32] = { 0 }, a[32][32];
queue <int >q;
void bfs(int i,int j) {
map[i][j] = 1;
q.push(i);
q.push(j);
while (!q.empty())
{
int w = q.front();
q.pop();
int e = q.front();
q.pop();
if (!a[w + 1][e] && !map[w + 1][e] && w != n + 1) { map[w + 1][e] = 1;q.push(w + 1);q.push(e); }
if (!a[w][e + 1] && !map[w][e + 1] && e != n+1) { map[w][e + 1] = 1;q.push(w);q.push(e + 1); }
if (!a[w][e - 1] && !map[w][e - 1] && e != 0) { map[w][e - 1] = 1;q.push(w);q.push(e - 1); }
if (!a[w - 1][e] && !map[w - 1][e] && w != 0) { map[w - 1][e] = 1;q.push(w - 1);q.push(e); }
}
}
int main() {
cin >> n;
a[32][32] = { 0 };
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= n;j++) {
cin >> a[i][j];
map[i][j] = a[i][j];
}
}
bfs(0, 0);
for (int k = 1;k <= n;k++) {
for (int m = 1;m <= n;m++) {
if (map[k][m] == 0)cout << "2" << " ";
else {
if (m == n)cout << a[k][m];
else cout << a[k][m] << " "; }
}
cout << endl;
}
return 0;
}