1. 程式人生 > >填塗顏色-洛谷

填塗顏色-洛谷

題目https://www.luogu.org/problemnew/show/P1162

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct node
{
	int x, y, step;
	node(){}
	node(int xx,int yy,int sstep): x(xx),y(yy),step(sstep){}
};
using namespace std;
const int z[4][2]={{1,0},{0,1},{0,-1},{-1,0}};
int a[100][100],book[100][100];int n;
void bfs(int x,int y,int step)
{
	queue<node>A;
	A.push(node(x,y,step));
	book[x][y]=3;
	while(!A.empty())
	{
		node b =A.front();
		A.pop();
		for(int i=0;i<4;i++)
		{
			int xx = b.x+z[i][0];
			int yy = b.y+z[i][1];
			int ss = b.step+1;
			if(a[xx][yy] == 0 && book[xx][yy] == 0 && xx >= 0 && yy>=0 && xx < n && yy <n)
			{
				book[xx][yy]=3;
				A.push(node(xx,yy,ss));
				
			}
		}
	}
	return ;
}
int main()
{
	
	scanf("%d",&n);int xstart,ystart;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++)
		{
			scanf("%d",&a[i][j]);
			
		}
	}
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++)
		{
			if(i == 0 || i == n-1 || j == 0 || j == n-1)
			{
				if(book[i][j] == 0 && a[i][j] != 1)
				{
					bfs(i,j,0);
				}
			}	
		}
	}
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++)
		{
			if(book[i][j] == 3)
			{
				printf("0 ");
			}
			else if(a[i][j] == 0)
			{
				printf("2 ");
			}
			else{
				printf("1 ");
			}
		}
		printf("\n");
	}
	return 0;
 }