百练OJ-Dungeon Master(BFS)

本文介绍了一个三维迷宫逃脱问题的解决方法,通过使用广度优先搜索算法,寻找从起点到终点的最短路径。该算法将迷宫表示为一个三维数组,并使用队列来存储待检查的位置。

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

#include<iostream>
#include<cstring>
#include<math.h>
#include<algorithm>
#include<array>
#include<queue>
using namespace std;
array<array<array<char, 34>, 34>, 34>dl = {'#'};
typedef pair<int, int>mid;
typedef pair<mid, int>P;
int main() {
	int l, r, c;
	while (cin >> l >> r >> c) {
		if (!l)
			break;
		int start_end[3][2];
		for (int i = 1; i <= l; i++) {
			for (int j = 1; j <= r; j++) {
				for (int k = 1; k <= c; k++) {
					cin >> dl[i][j][k];
					if (dl[i][j][k] == 'S') {
						start_end[0][0] = i;
						start_end[1][0] = j;
						start_end[2][0] = k;
						//dl[i][j][k] = '#';
					}
					if (dl[i][j][k] == 'E') {
						start_end[0][1] = i;
						start_end[1][1] = j;
						start_end[2][1] = k;
						//dl[i][j][k] = '#';
					}

				}
			}
		}
		queue<P> q;
		q.push(P(mid(start_end[0][0], start_end[1][0]), start_end[2][0]));
		array<array<array<int, 34>, 34>, 34>cost = { 0 };
		bool fg = true;
		while (!q.empty()) {
			P point = q.front();
			q.pop();
			mid pre = point.first;
			int L = pre.first;
			int R = pre.second;
			int C = point.second;
			int costnow = cost[L][R][C];
	
			if (L == start_end[0][1] && R == start_end[1][1] && C == start_end[2][1]) {//找到了
				printf("Escaped in %d minute(s).\n", costnow);
				fg = false;
				break;
			}
			
			if (dl[L - 1][R][C] == '.'|| dl[L - 1][R][C] == 'E') {
				dl[L - 1][R][C] = '#';
				cost[L - 1][R][C]=costnow+1;
				q.push(P(mid(L - 1, R), C));
			}


			if (dl[L + 1][R][C] == '.'|| dl[L + 1][R][C] == 'E') {
				dl[L + 1][R][C] = '#';
				cost[L + 1][R][C] = costnow + 1;
				q.push(P(mid(L + 1, R), C));
			}

			if (dl[L][R + 1][C] == '.'|| dl[L][R + 1][C] == 'E') {
				dl[L][R+1][C] = '#';
				cost[L][R + 1][C] = costnow + 1;
				q.push(P(mid(L, R + 1), C));
			}

			if (dl[L][R - 1][C] == '.'|| dl[L][R - 1][C] == 'E') {
				dl[L][R - 1][C] = '#';
				cost[L][R - 1][C] = costnow + 1;
				q.push(P(mid(L, R - 1), C));
			}
			if (dl[L][R][C + 1] == '.'|| dl[L][R][C + 1] == 'E') {
				dl[L][R][C+1] = '#';
				cost[L][R][C + 1] = costnow + 1;
				q.push(P(mid(L, R), C + 1));
			}
			if (dl[L][R][C - 1] == '.'|| dl[L][R][C - 1] == 'E') {
				dl[L][R][C - 1] = '#';
				cost[L][R][C - 1] = costnow + 1;
				q.push(P(mid(L, R), C - 1));
			}
		}
		if (fg) {
			cout << "Trapped!" << endl;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值