Codeforces-377A Maze(深度优先搜索)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值