You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides.
Is an escape possible? If yes, how long will it take?
Input
The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size).
L is the number of levels making up the dungeon.
R and C are the number of rows and columns making up the plan of each level.
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a '#' and empty cells are represented by a '.'. Your starting position is indicated by 'S' and the exit by the letter 'E'. There's a single blank line after each level. Input is terminated by three zeroes for L, R and C.
Output
Each maze generates one line of output. If it is possible to reach the exit, print a line of the form
Escaped in x minute(s).
where x is replaced by the shortest time it takes to escape.
If it is not possible to escape, print the line
Trapped!
Sample Input
3 4 5 S.... .###. .##.. ###.# ##### ##### ##.## ##... ##### ##### #.### ####E 1 3 3 S## #E# ### 0 0 0
Sample Output
Escaped in 11 minute(s). Trapped!
代码
#include <iostream>
#include <cstring>
#include<cstdio>
#include <stack>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
char a[32][32][32];
int vis[32][32][32];
int dir[6][3] = { {1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1} };
int flag;
int ans;
int n, m, k;
struct node {
int x, y, z, s;
}e[32];
node first;
int t;
void bfs() {
queue<node>q;
q.push(first);
while (!q.empty()) {
node now = q.front();
q.pop();
if (a[now.x][now.y][now.z] == 'E') {
t = now.s;
flag = 1;
}
node next;
next.s = now.s + 1;
for (int i = 0; i < 6; i++) {
int x = now.x + dir[i][0];
int y = now.y + dir[i][1];
int z = now.z + dir[i][2];
if (x >= 0 && x < n&&y >= 0 && y < m&&z >= 0 && z < k&&a[x][y][z] == '.'&&vis[x][y][z] == 0 || a[x][y][z] == 'E')
{
next.x = x;
next.y = y;
next.z = z;
q.push(next);
vis[x][y][z] = 1;
}
}
}
}
int main() {
while (cin >> n >> m >> k) {
if (n == 0 && m == 0 && k == 0) {
break;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
for (int l = 0; l < k; l++) {
cin >> a[i][j][l];
}
}
}
ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
for (int l = 0; l < k; l++) {
if (a[i][j][l] == 'S')
{
first.x = i, first.y = j, first.z = l, first.s = 0;
vis[i][j][l] = 1;
}
}
}
}
flag = 0;
bfs();
if (flag) {
printf("Escaped in %d minute(s).\n", t);
}
else printf("Trapped!\n");
}
return 0;
}
本文介绍了一个3D迷宫逃脱问题的解决方法,利用广度优先搜索算法寻找从起点到出口的最短路径。输入包含多个迷宫,每个迷宫由不同层数、行数和列数组成,通过字符描述单元格状态。输出最快逃脱所需的时间或无法逃脱的信息。
452

被折叠的 条评论
为什么被折叠?



