Codeforces-377A Maze
这道题是一道比较简单的思维题,只需要使用dfs或者bfs搜索哪些块不用删除,而剩下的块则必须删除,因此我想到的解法有两种,一种是使用DFS遍历,一种是使用BFS遍历,提交的时候使用的水BFS。具体代码如下,因为代码都比较直观,不再多做解释,请见谅。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
int n ,m, k , num;
char maze[600][600]{ 0 };
bool book[600][600]{ 0 };
int mov[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };
void bfs( int x , int y ) {
struct Biple {
int x, y;
Biple(int x, int y):x(x) , y(y) {
}
};
queue< Biple > que;
que.push(Biple(x, y));
int cnt = 1;//已经选择了bfs的开始的点,所以是1.
while (!que.empty()) {
if (cnt >= num - k) break;
Biple tmp = que.front();
que.pop();
for (int i = 0; i < 4; i++) {
int xx = tmp.x + mov[i][0];
int yy = tmp.y + mov[i][1];
if (xx < 1 || xx > n || yy < 1 || yy > m) continue;
if (!book[xx][yy] && maze[xx][yy] == '.') {
que.push(Biple(xx, yy));
book[xx][yy] = 1;
cnt++;
//cout << "xx : " << xx << "yy : " << yy << endl;
if (cnt >= num - k) break;
}
}
}
}
int main() {
while (cin >> n >> m >> k) {
int x, y;
num = 0;
for (int i = 1; i <= n; i++) {
scanf("%s", maze[i] + 1);
for (int j = 1; j <= m; j++) {
if (maze[i][j] == '.') {
num++;
x = i;
y = j;
}
}
}
memset(book, 0, sizeof(book));
book[x][y] = 1;//这个点已经做出了选择,因此需要标记为true。
bfs(x, y);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (maze[i][j] == '.') {
if (book[i][j]) cout << ".";
else cout << 'X';
}
else {
cout << maze[i][j];
}
}
cout << endl;
}
}
return 0;
}