題目描述
由數字0 組成的方陣中,有一任意形狀閉合圈,閉合圈由數字1構成,圍圈時只走上下左右4個方向。現要求把閉合圈內的所有空間都填寫成2.例如:6X6的方陣(n=6),塗色前和塗色後的方陣如下:
0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 1 1 0 0 1 1 1 1
0 1 1 0 0 1 0 1 1 2 2 1
1 1 0 0 0 1 1 1 2 2 2 1
1 0 0 0 0 1 1 2 2 2 2 1
1 1 1 1 1 1 1 1 1 1 1 1
輸入輸出格式
輸入格式:
每組測試數據第一行一個整數:n。其中n(1<=n<=30)
接下來n行,由0和1組成的nXn的方陣。
方陣內只有一個閉合圈,圈內至少有一個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
很簡單的BFS,莫名的WA了幾次···
就是先把0全部置爲2,從四周開始找,然後bfs,碰到2就改爲0,而且因爲有數字限制,不需要vis數組了
code:
#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
const int N=35,dx[4]={0,0,1,-1},dy[4]={1,-1,0,0};
struct node
{
int x,y;
}x;
int a[N][N],n;
queue<node>q;
void bfs(int sx,int sy)
{
int fx,fy,i;
a[sx][sy]=0;
q.push((node){sx,sy});
while(!q.empty())
{
x=q.front();
q.pop();
for(i=0;i<4;i++)
{
fx=x.x+dx[i];
fy=x.y+dy[i];
if(fx>=1&&fx<=n&&fy>=1&&fy<=n&&a[fx][fy]==2)
{
a[fx][fy]=0;
q.push((node){fx,fy});
}
}
}
}
int main()
{
int i,j;
cin>>n;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
cin>>a[i][j];
if(a[i][j]==0)
a[i][j]=2;
}
for(i=1;i<=n;i++)
if(a[1][i]==2)
bfs(1,i);
for(i=1;i<=n;i++)
if(a[i][1]==2)
bfs(i,1);
for(i=1;i<=n;i++)
if(a[n][i]==2)
bfs(n,i);
for(i=1;i<=n;i++)
if(a[i][n]==2)
bfs(i,n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
return 0;
}