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!
第一道没看别人解析写出的bfs类型题,可以看成一个三维的迷宫,所以用一个三维的数组存路况,再用bfs逐个访问即可,与其他bfs访问一样,因为随着访问的进行,步数会逐渐增加,所以最先遇到出口的那条路即为最短路线。
ac代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <cstdlib>
#include <queue>
#include<iomanip>
using namespace std;
char p[35][35][35];
int ji[35][35][35],xxx,sum,ant,l,r,c;
int r1[6] = { 0,0,0,0,1,-1 }, r2[6] = { 1,-1,0,0,0,0 }, r3[6] = { 0,0,1,-1,0,0 };//对于每个点,有东西南北上下可以走。
struct asd
{
int a,b,d,t;
}q[30000];//t记在该路线走了多少步。
void bfs(int t,int u,int v)
{
ji[t][u][v] = 1;
q[0].a = t; q[0].b = u; q[0].d = v; q[0].t = 0;
int x, y, z;
ant++;
while (sum<ant)
{
for (int i = 0; i < 6; i++)
{
q[ant].a=x = r1[i] + q[sum].a;
q[ant].b=y = r2[i] + q[sum].b;
q[ant].d=z = r3[i] + q[sum].d;
q[ant].t = q[sum].t + 1;
if (x >= 0 && x < l&&y >= 0 && y < r&&z >= 0 && z < c&&ji[x][y][z] == 0 && p[x][y][z] != '#')//某点最先被访问的路线是到该点的最短路线,其他路线后来就不必再访问它了,再有效区域外和碰到#也不必走了。
{
ji[x][y][z] = 1;
ant++;
if (p[x][y][z]=='E')
{
ant--;
xxx=1;//记找到出口了
return;
}
}
}
sum++;
}
}
int main()
{
int w, e, h;
while (cin >> l >> r >> c)
{
xxx =ant=sum = 0;
memset(ji, 0, sizeof(ji));
if (l == 0 && r == 0 && c == 0)break;
for (int i = 0; i < l; i++)
{
for (int j = 0; j < r; j++)
{
for (int k = 0; k < c; k++)
{
cin >> p[i][j][k];
if (p[i][j][k] == 'S')///记起点
{ w = i; e = j; h = k;
}
}
}
}
bfs(w,e,h);
if (xxx)cout <<"Escaped in "<<q[ant].t<<" minute(s)."<< endl;
else cout << "Trapped!" << endl;
}
}