首页 > 代码库 > Codeforces Round #222 (Div. 1)A. Maze(深搜)
Codeforces Round #222 (Div. 1)A. Maze(深搜)
传送门
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 exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Input
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.
Output
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.
Sample Input
3 4 2
#..#
..#.
#...
3 4 2
#..#
..#.
#...
Sample Output
3 4 2
#..#
..#.
#...
3 4 2
#..#
..#.
#...
思路
题意:
给出一个迷宫,‘.‘ 表示通路,‘#‘ 表示城墙,要求将k个‘.‘转换成‘#‘,使得剩下的‘.‘仍然是联通的
题解:
深搜,假设共有s个‘.‘那么搜索得到的s-k个点必然是联通的,那么只要将剩下的‘.‘转换成‘#‘就行了。
#include<bits/stdc++.h>using namespace std;const int maxn = 505;char maze[maxn][maxn];bool vis[maxn][maxn];int n, m, k;int dx[4] = {0, -1, 0, 1};int dy[4] = { -1, 0, 1, 0};void dfs(int mx, int my){ vis[mx][my] = 1; for (int i = 0; i < 4; i++) { int nx = mx + dx[i], ny = my + dy[i]; if (0 <= nx && nx < n && 0 <= ny && ny < m && maze[nx][ny] == ‘.‘ && !vis[nx][ny]) { dfs(nx, ny); } } if (k > 0) maze[mx][my] = ‘X‘,k--;}int main(){ memset(vis, 0, sizeof(maze)); bool flag = false; scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < n; i++) scanf("%s", maze[i]); for (int i = 0; i < n && !flag; i++) { for (int j = 0; j < m; j++) { if (maze[i][j] == ‘.‘) { dfs(i,j); flag = true; break; } } } for (int i = 0;i < n;i++) printf("%s\n",maze[i]); return 0;}
Codeforces Round #222 (Div. 1)A. Maze(深搜)