题目描述
由数字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。
//感谢黄小U饮品指出本题数据和数据格式不一样. 已修改(输入格式)
输出格式
已经填好数字2的完整方阵。
输入输出样例
输入 #1复制
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
输出 #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>
using namespace std;
#define check(x , y) tempx >= 1 && tempx <= n && tempy >= 1 && tempy <= n
int n , arr[35][35] , book[35][35] , head , tail;
int d[4][2] = {0 , 1 , 0 , -1 , 1 , 0 , -1 , 0};
struct Queue{
int x , y;
};
Queue q[10000];
void bfs(int a , int b){
q[head].x = a;
q[tail].y = b;
book[a][b] = 1;
arr[a][b] = 0;
tail++;
while(head < tail){
for(int i = 0 ; i < 4 ; i++){
int tempx = q[head].x + d[i][0];
int tempy = q[head].y + d[i][1];
if(check(x , y) && arr[tempx][tempy] == 2 && !book[tempx][tempy]){
q[tail].x = tempx;
q[tail].y = tempy;
book[tempx][tempy] = 1;
arr[tempx][tempy] = 0;
tail++;
}
}
head++;
}
}
int main(){
cin >> n;
for(int i = 1 ; i <= n ; i++){
for(int j = 1 ; j <= n ; j++)
cin >> arr[i][j];
}
for(int i = 1 ; i <= n ; i++){
for(int j = 1 ; j <= n ; j++){
if(arr[i][j] == 0) arr[i][j] = 2;
}
}
head = tail = 1;
for(int i = 1 ; i <= n ; i++){
if(arr[1][i] == 2) bfs(1 , i);
if(arr[n][i] == 2) bfs(n , i);
if(arr[i][1] == 2) bfs(i , 1);
if(arr[i][n] == 2) bfs(i , n);
}
for(int i = 1 ; i <= n ; i++){
for(int j = 1 ; j <= n ; j++)
cout << arr[i][j] << " ";
cout << endl;
}
return 0;
}