POJ 2251(BFS模板)

该博客讨论了一个名为'DungeonMaster'的编程问题,其中涉及在多层迷宫中寻找从起点到终点的最短路径。文章指出初始理解的限制——只能从上层向下层移动,但实际上可以从下层返回上层。作者通过广度优先搜索(BFS)算法解决这个问题,并提供了详细的代码实现。在每层迷宫中,算法会检查所有可能的移动方向,直到找到目标位置或确定无法逃脱。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Dungeon Master - POJ 2251 - Virtual Judge

此题有坑,一开始以为只能从上往下走,结果是有可能从下一层的迷宫回到上一层的。

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#include <map>
typedef long long ll;
using namespace std;
const int MN = 505;
const int MAXN = 1000005;
const int INF = 0x3f3f3f3f;

int L, R, C;
int ans;
int vis[35][35][35];
char s[35][35][35];
struct step {
	int x, y, c, sp;
	step(int tx, int ty, int tc, int ts): x(tx), y(ty), c(tc), sp(ts) {

	}
};

int gox[6] = {0, 1, 0, 0, 0, -1};

int goy[6] = {1, 0, 0, 0, -1, 0};

int goc[6] = {0, 0, 1, -1, 0, 0};
int ec, ex, ey;

int bfs(int c, int x, int y) {
	queue<step> que;
	que.push(step(x, y, c, 0));
	while (!que.empty()) {
		step p = que.front();
		que.pop();
		//printf("%d %d %d %d\n", p.x, p.y, p.c, p.sp);
		if (p.x == ex && p.y == ey && p.c == ec) {
			return p.sp;
		}
		int tx, ty, tc;
		for (int i = 0; i <= 5; i++) {
			tx = p.x + gox[i];
			ty = p.y + goy[i];
			tc = p.c + goc[i];
			if (tx >= 1 && tx <= R && ty >= 1 && ty <= C && tc >= 1 && tc <= L && s[tc][tx][ty] != '#' && vis[tc][tx][ty] == 0) {
				vis[tc][tx][ty] = 1;
				que.push(step(tx, ty, tc, p.sp + 1));
				//printf();
			}
		}
	}
	return 0;
}

void solve() {
	ans = 0;
	memset(vis, 0, sizeof(vis));
	int tx, ty, tc;
	for (int i = 1; i <= L; i++) {
		for (int j = 1; j <= R; j++) {
			for (int k = 1; k <= C; k++) {
				scanf(" %c", &s[i][j][k]);
				if (s[i][j][k] == 'S') {
					tc = i;
					tx = j;
					ty = k;
				}
				if (s[i][j][k] == 'E') {
					ec = i;
					ex = j;
					ey = k;
				}
			}
		}
	}
	int res = bfs(tc, tx, ty);
	if (res) {
		printf("Escaped in %d minute(s).\n", res);
	} else {
		printf("Trapped!\n");
	}
}

int main() {
	while (~scanf("%d %d %d", &L, &R, &C)) {
		if (L == 0 && R == 0 && C == 0) {
			break;
		}
		solve();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值