题目描述
由数字0组成的方阵中,有一任意形状闭合圈,闭合圈由数字1构成,围圈时只走上下左右4个方向。现要求把闭合圈内的所有空间都填写成2.例如:6×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
代码:
#include<iostream>
using namespace std;
#include<cstring>
#include<queue>
int xx[] = { 0,-1,0,1 };
int yy[] = { 1,0,-1,0 };
//刚好是坐标的上下左右
int mp[40][40];
int visit[40][40];//标记是否访问过
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> mp[i][j];//输入矩阵
}
}
queue <int>x;//x队列
queue<int>y;//y队列
x.push(0); y.push(0);
visit[0][0] = 1;
while (!x.empty())
{
for (int i = 0; i < 4; i++)
{
int dx = x.front() + xx[i];
int dy = y.front() + yy[i];
if (dx >= 0 && dy >= 0 && dx <= n + 1 && dy <= n + 1 && mp[dx][dy] == 0 && !visit[dx][dy])
{
x.push(dx);
y.push(dy);
visit[dx][dy] = 1;
}
}
x.pop();
y.pop();
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (mp[i][j] == 0 && visit[i][j] == 0)
cout << 2 << " ";
else
cout << mp[i][j] << " ";
}
cout << endl;
}
return 0;
}