Dungeon Master
Problem Description
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的拓展题,往常我们写的都是一层,而这道题却有了一个“上楼”的操作,其实也还好,这道题相当于多写一个z坐标,除了上下左右,还有上下楼,当时遇到了一个小问题就是栈定义在bfs函数外,然后在走到终点时return了,栈在未空的情况下return,导致下一组测试出现了问题,后来在大佬的帮助下,找到了这个问题,将栈的初始化写在了bfs函数内,每次都重新初始化,解决了这个问题。
代码如下:
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
int d[6][3] = {0,1,0,0,-1,0,1,0,0,-1,0,0,0,0,1,0,0,-1}; //上下左右以及上楼下楼
typedef struct
{
int x,y,z;
int step;
}node;
node ss,ee;
int l,r,c;
int st;
char mapp[35][35][35];
int bfs(node a)
{
queue<node> s;
int i,j;
node temp,t;
s.push(a);
if(a.x==ee.x&&a.y==ee.y&&a.z==ee.z)
{
st = t.step;
return t.step;
}
mapp[a.x][a.y][a.z] = '#';
while(!s.empty())
{
temp=s.front();
s.pop();
t.step=temp.step+1;
for(i=0;i<6;i++)
{
t.x=temp.x+d[i][0];
t.y=temp.y+d[i][1];
t.z=temp.z+d[i][2];
if(t.x>=0&&t.x<r&&t.y>=0&&t.y<c&&t.z>=0&&t.z<l&&mapp[t.x][t.y][t.z]!='#')
{
mapp[t.x][t.y][t.z] = '#';
if(t.x==ee.x&&t.y==ee.y&&t.z==ee.z)
{
return t.step; //走到终点则return步数
}
s.push(t);
}
}
}
return 0; //走不到终点则return 0
}
int main()
{
int i,j,k;
int flagg;
while(cin>>l>>r>>c&&l&&r&&c)
{
st=0;
flagg=0;
for(k=0;k<l;k++)
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cin>>mapp[i][j][k];
if(mapp[i][j][k]=='S')
{
ss.x=i;ss.y=j;ss.z=k;
ss.step=0; //初始化步数
}
if(mapp[i][j][k]=='E')
{
ee.x=i;ee.y=j;ee.z=k;
}
}
}
}
flagg = bfs(ss);
if (flagg==0)
cout << "Trapped!" << endl;
else
cout << "Escaped in " << flagg << " minute(s)." << endl;
}
return 0;
}