A. Maze
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.
Sample Input
3 4 2
#..#
..#.
#...
#.X#
X.#.
#...
5 4 5
#...
#.#.
.#..
...#
.#.#
#XXX
#X#.
X#..
...#
.#.#
题目大意:给你n,m和k,n和m代表矩阵的大小,然后k是需要填的数量。有一个人有一个联通的房间,'#'代表墙,'.'代表可以走的路,然后再往图中填k个墙壁之后图还是联通的,输出填的方案。
题目解析:我们随意找一个为空地的地方开始跑bfs,跑到bfs跑不到的地方结束,按照bfs序列我们得到了一个类似于栈的序列,我们再依次按照bfs序列把空地填回去就可以了。
#include <algorithm> #include <iostream> #include <numeric> #include <cstring> #include <iomanip> #include <string> #include <vector> #include <cstdio> #include <bitset> #include <queue> #include <stack> #include <cmath> #include <map> #include <set> #define LL __int64 #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define Pair pair<int,int> const int INF = 0x3f3f3f3f; using namespace std; char arr[505][505]; bool vis[505][505]; int dx[] = {0,0,1,-1}; int dy[] = {1,-1,0,0}; int main(){ int n,m,k,sx,sy; while(~scanf("%d %d %d",&n,&m,&k)){ stack<Pair>S; queue<Pair>Q; memset(vis,false,sizeof(vis)); sx = sy = -1; for(int i=0;i<n;i++){ scanf("%s",arr[i]); if(sx == -1){ for(int j=0;j<m;j++){ if(arr[i][j] == '.'){ sx = i;sy = j; break; } } } } vis[sx][sy] = true; S.push(make_pair(sx,sy)); Q.push(make_pair(sx,sy)); while(!Q.empty()){ Pair ant = Q.front();Q.pop(); for(int i=0;i<4;i++){ int nowx = ant.first + dx[i]; int nowy = ant.second + dy[i]; if(nowx >= 0 && nowx < n && nowy >=0 && nowy < m && arr[nowx][nowy] == '.' && !vis[nowx][nowy]){ vis[nowx][nowy] = true; S.push(make_pair(nowx,nowy)); Q.push(make_pair(nowx,nowy)); } } } while(!S.empty()){ if(k){ Pair ant = S.top();S.pop(); if(arr[ant.first][ant.second] == '.'){ arr[ant.first][ant.second] = 'X'; k -= 1; } } else{ break; } } for(int i=0;i<n;i++){ printf("%s\n",arr[i]); } } return 0; }