luogu1162:填涂颜色:宽搜+封边

题目连接:该题是luogu试炼场的2-7:T2


题目大意:
1 给出一个0,1棋盘,要求将被1包围的部分,改写成2。
 


解题思路:
1 宽搜的元问题:类似细胞分裂;
2 对于四个边的每个点进行一次宽搜,将能触碰到边缘的点都标记成-1;
3 输出的时候,-1和1都不需要涂色,其他位置就是被1包含的,涂色成2;


上代码:
 

//luogu1162:填涂颜色 

//棋盘上的宽搜元问题
//封边处理 

#include

int ma[50][50],n,tou,wei;;
struct nod{int x,y; }l[300];

int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};

void bfs(int x,int y)//将相邻的0,都涂成-1 
{
	tou=1;wei=2;
	l[tou].x=x;
	l[tou].y=y;
	while(tou=1&&nx<=n&&ny>=1&&ny<=n)
			{
				if(ma[nx][ny]==0) 
				{
					ma[nx][ny]=-1;
					l[wei].x=nx;
					l[wei].y=ny;
					wei++;
				}
			}
		}
		tou++;
	}
}

int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			scanf("%d",&ma[i][j]);
		}
	}
	for(int i=1;i<=n;i++)//封边 
	{
		if(ma[1][i]==0) bfs(1,i);
		if(ma[n][i]==0) bfs(n,i);
		if(ma[i][1]==0) bfs(i,1);
		if(ma[i][n]==0) bfs(i,n);
	}

	//输出 
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			if(ma[i][j]==-1) printf("0 ");
			else if(ma[i][j]==0) printf("2 ");
			else printf("%d ",ma[i][j]);
		}
		printf("\n");
	}
	return 0;
}

 

你可能感兴趣的:(题解,宽搜,题表,luogu,大礼包,luogu1162,填涂颜色,宽搜)