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.
The first line contains three integers n, m, k (1 ≤ n, m ≤ 500, 0 ≤ k < s), where n andm 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.
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.
3 4 2 #..# ..#. #...
#.X# X.#. #...
5 4 5 #... #.#. .#.. ...# .#.#
#XXX #X#. X#.. ...# .#.#
思路 : 如果在 . 里找X 不太方便,可以转换一下,
1 把所有的 ‘.’ 先变成 ‘X’
2 问题转化为在X中找s-k个字符 ‘.’ 这样就可以随便找个X开始广搜,直到找够数目,因为题目说了,一定有解.
#include <cstdio> #include <cstring> #include <stack> #include <queue> #include <iostream> using namespace std; typedef struct node{ int x,y; node (int a,int b){ x = a,y = b; } }node; int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}}; char mp[510][510]; int num,cur,m,n; void bfs(int x,int y) { node tmp(x,y) ; mp[x][y] = '.'; queue <node> q; q.push(tmp); if(++cur == num) return; while(!q.empty()) { tmp = q.front(); q.pop(); for(int i = 0; i < 4; i++) { int x_ = tmp.x + dir[i][0]; int y_ = tmp.y + dir[i][1]; if(x_ < 1 || x_ > m || y_ < 1|| y_ > n) continue; if(mp[x_][y_] == '#' || mp[x_][y_] == '.') continue; mp[x_][y_] = '.'; node nd(x_,y_); q.push(nd); if(++cur == num) return; } } } void showmap() { for(int i = 1; i <= m; i++) { for(int j = 1; j <= n; j++) { printf("%c",mp[i][j]); } printf("\n"); } } int main() { int x,y,k; scanf("%d%d%d",&m,&n,&k); for(int i = 1; i <= m; i++) for(int j = 1; j <= n; j++) { cin >> mp[i][j]; if(mp[i][j] == '.') { num ++; mp[i][j] = 'X'; x = i,y = j; } } num -= k ,cur = 0; bfs(x,y); showmap(); return 0; }