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.
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;
}