Description
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 exactlyk 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 letters 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.
Sample Input
3 4 2 #..# ..#. #...
#.X# X.#. #...
5 4 5 #... #.#. .#.. ...# .#.#
#XXX #X#. X#.. ...# .#.# 此题我的解法是用queue容器,先计算出需要保留的'.'数量,再随机抽取一.点作为出发点,然后遍历出需要的数量,剩下的输出时全部输出为X。#include <cstdio> #include <queue> #include <cstring> using namespace std; int n,m,k,u,v,shuliang;//数量记录需要连接的数量(总的.数量-k) int u,v;//出发点位置 bool visit[512][512];//记录是否读取过 char _map[512][512];//记录输入的迷宫 struct Point{ int x; int y; };//记录坐标 int dx[]={1,-1,0,0}; int dy[]={0,0,1,-1}; bool OK(struct Point a)//判断坐标是否可取 { return a.x>=0 && a.x<m && a.y>=0 && a.y<n && !visit[a.x][a.y]; } void BFS() { int w=1; queue<Point> QE; Point top,t; shuliang=shuliang-k;//统计需要保留的.数量 top.x=u; top.y=v; QE.push(top); if(shuliang!=0)//下面算法的漏洞,没法判断全部为x时的情况 visit[u][v]=1; while(QE.empty()==false && shuliang!=0) { top=QE.front(); QE.pop(); for(int i=0;i<4;i++) { t.x=top.x+dx[i]; t.y=top.y+dy[i]; if(OK(t) && _map[t.x][t.y]=='.' && w<shuliang) { QE.push(t); visit[t.x][t.y]=1; w++; }//此处为核心一,把需要保留的位置遍历一遍,把visit变为1,后面修改时visit为0的就可直接输出x if(w==shuliang) return; } } } int main() { int i,w=0; char s[512]; scanf("%d%d%d",&n,&m,&k); memset(visit,0,sizeof(visit)); memset(_map,0,sizeof(_map)); shuliang=0; for(i=0;i<n;i++) { scanf("%s",s); for(int j=0;j<m;j++) { _map[j][i]=s[j]; if(s[j]=='.') shuliang++; if(w==0 && s[j]=='.') { u=j; v=i; w=1;//找到随机点,并防止重复寻找 } } } BFS(); for(i=0;i<n;i++)//输出 { for(int j=0;j<m;j++) { if(visit[j][i]==0 && _map[j][i]=='.')//没遍历过得 . 就输出x printf("X"); else printf("%c",_map[j][i]); } printf("\n"); } }