Description
由數字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
思路:
- bfs,對於不是閉圈的點,對這個點進行bfs,一定能走到迷宮的邊邊
- 而是閉圈的點,不管怎麼走,也走不到邊邊。
- 找到一個閉圈之後,就可以塗色了,flag=1,再進行一次bfs。
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define mp make_pair
#define mst(x,a) memset(x,a,sizeof(x))
#define fi first
#define se second
#define For(i,x,y) for(register int i=(x); i<=(y); i++)
using namespace std;
typedef pair<int,int>pa;
int g[40][40],vis[40][40];
int dx[4]= {0,0,-1,1};
int dy[4]= {1,-1,0,0};
int flag=0,n;
bool bfs(int x, int y)
{
mst(vis,0);
queue<pa>q;
q.push(mp(x,y));
vis[x][y]=1;
while(!q.empty())
{
int cx=q.front().fi,cy=q.front().se;
if(flag)g[cx][cy]=2;
q.pop();
for(int i=0; i<4; i++)
{
int tx=cx+dx[i],ty=cy+dy[i];
if(tx>=1&&tx<=n&&ty>=1&&ty<=n&&g[tx][ty]==0&&!vis[tx][ty])
{
vis[tx][ty]=1;
q.push(mp(tx,ty));
if(tx==1||tx==n||ty==1||ty==n)
{
return false;
}
}
}
}
return true;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
For(i,1,n)
{
For(j,1,n)cin>>g[i][j];
}
For(i,1,n)
{
For(j,1,n)
{
if(g[i][j]==0&&bfs(i,j))
{
flag=1;
bfs(i,j);
flag=0;
}
}
}
For(i,1,n)
{
For(j,1,n)
{
cout<<g[i][j]<<' ';
}
cout<<endl;
}
return 0;
}