题目:Maze(思维+BFS)

版权声明:本文为博主原创文章,欢迎转载。如有问题,欢迎指正。 https://blog.csdn.net/weixin_42172261/article/details/87002107

题目描述:
Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn’t like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.

Input
The first line contains three integers n, m, k (1 ≤ n, m ≤ 500, 0 ≤ k < s), where n and m are the maze’s height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze.
Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals “.”, then the corresponding cell is empty and if the character equals “#”, then the cell is a wall.

Output
Print n lines containing m characters each: the new maze that fits Pavel’s requirements. Mark the empty cells that you transformed into walls as “X”, the other cells must be left without changes (that is, “.” and “#”).
It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.

思路:
本来s个联通的方块,把其中k个换成墙壁后生下的s-k个仍然联通。
可以想成从一个点开始广搜,搜索到s-k个方块就停下,搜索的过程中标记满足条件的点。最后maze数组的元素有’#’、’.‘被标记、’.'没被标记。没被标记的打成X就好了。

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

char a[505][505];
int b[505][505];
struct point{
	int x;
	int y;
}que[250005];

int n, m, k, kk=0;
int nextt[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int head=1, tail=1;

void bfs(int i, int j)
{
	int count=0, tx, ty;
	b[i][j]=1;
	count++;
	que[tail].x=i;
	que[tail].y=j;
	tail++;
	if (count==kk-k)
		return;
	while (head<tail){
		for (int t=0; t<4; t++){
			tx=que[head].x+nextt[t][0];
			ty=que[head].y+nextt[t][1];
			if (tx<0||tx>=n||ty<0||ty>=m)	
				continue;
			if (a[tx][ty]=='.' && b[tx][ty]==0){
				b[tx][ty]=1;
				que[tail].x=tx;
				que[tail].y=ty;
				tail++;
				count++;
			}
			if (count==kk-k){
				return;
			}
		}
		head++;
	} 
}
int main()
{
	int bx, by, i, j;
	cin>>n>>m>>k;
	kk=0;
	for (i=0; i<n; i++){
		scanf("%s", a[i]);
		for (j=0; j<m; j++){
			if (a[i][j]=='.'){
				kk++;
				bx=i;
				by=j;
			}
		}
	}
	bfs(bx, by);
	for (int i=0; i<n; i++){
		for (int j=0; j<m; j++){
			if (a[i][j]=='.' && b[i][j]==0)	printf("X");
			else	printf("%c", a[i][j]);
		}
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42172261/article/details/87002107