Maze(dfs 回溯)

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 nmk (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.

Examples

Input

3 4 2
#..#
..#.
#...

Output

#.X#
X.#.
#...

Input

5 4 5
#...
#.#.
.#..
...#
.#.#

Output

#XXX
#X#.
X#..
...#
.#.#

題意:給你三個數字n,m,k;讀入一個n行m列的圖,#代表牆,"."代表可以通過的路,然後讓你把k個“.”變成'X',使得剩下的‘.’能夠連成一個整體。(變成“X”的“.”就不能走了)

通過遍歷找到圖中的'.',開始深搜,一直搜到某條路徑完成,在遞歸退回的過程中令‘.’變成“X”(路徑的末尾),根據先行遍歷的方向順序不同,得到的新地圖可能會不同,所以題目說給出一種就可以。

我是按照右 左 下 上 的順序進行深搜的。

#include<iostream>
#include<cstring>
#include<string>
using namespace std;
char mp[505][505];
int vis[505][505],n,m,k;
int dir[4][2]= {0,1,0,-1,1,0,-1,0};//右 左 下 上 
void dfs(int x,int y) {
	if(k==0) return ;
	for(int i=0; i<4; i++) {
		int xx=x+dir[i][0];
		int yy=y+dir[i][1];
		if(xx<1||xx>n||yy<1||yy>m)continue;
		if(!vis[xx][yy]&&mp[xx][yy]=='.') {
			vis[xx][yy]=1;
			dfs(xx,yy);
			//vis[xx][yy]=0;這一句有沒有都行,有的回溯問題中,標記必須歸零,這道題想了一下。
           /*如果從(xx,yy)退回,k!=0時,(xx,yy)接着變成了"X",那還用vis[xx][yy]=0幹嘛,
           直接都不能走了。如果k==0,早已經退出dfs.所以標記歸零的作用在這裏沒體現*/
			if(k) {
				mp[xx][yy]='X';
				k--;
			}
		}
	}
}
int main() {
	while(~scanf("%d %d %d",&n,&m,&k)) {
		memset(vis,0,sizeof(vis));
		getchar();
		for(int i=1; i<=n; i++) {
			for(int j=1; j<=m; j++) {
				scanf("%c",&mp[i][j]);
				if(mp[i][j]=='#') vis[i][j]=1;
			}
			getchar();
		}
		for(int i=1; i<=n; i++) {
			for(int j=1; j<=m; j++) {
				if(mp[i][j]=='.') {
					vis[i][j]=1;
					dfs(i,j);
					break;
				}
			}
		}
		for(int i=1; i<=n; i++) {
			for(int j=1; j<=m; j++) {
				printf("%c",mp[i][j]);
			}
			printf("\n");
		}
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章