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模板就可以解决。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
#define IOS ios::sync_with_stdio(false);cin.tie(0);
const int N=35;
char g[N][N][N];
int d[N][N][N];
int l,r,c;
int dir[6][3]={{-1,0,0},{1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
struct node{
int x,y,z;
};
node start,en;
bool flag;
int bfs(){
d[start.z][start.x][start.y]=0;
queue<node> q;
q.push(start);
while(q.size()){
node p=q.front();
node nex;
q.pop();
for(int i=0;i<6;i++){
nex.x=p.x+dir[i][0];
nex.y=p.y+dir[i][1];
nex.z=p.z+dir[i][2];
if(nex.x>=0&&nex.y>=0&&nex.z>=0&&nex.x<r&&nex.y<c&&nex.z<l&&g[nex.z][nex.x][nex.y]!='#'&&d[nex.z][nex.x][nex.y]==-1){
d[nex.z][nex.x][nex.y]=d[p.z][p.x][p.y]+1;
if(nex.x==en.x&&nex.y==en.y&&nex.z==en.z) return d[nex.z][nex.x][nex.y];
q.push(nex);
}
}
}
return -1;
}
int main(){
IOS;
while(cin>>l>>r>>c&&l&&r&&c){
flag=false;
memset(d,-1,sizeof d);
for(int i=0;i<l;i++){
for(int j=0;j<r;j++){
for(int t=0;t<c;t++){
cin>>g[i][j][t];
if(g[i][j][t]=='S'){
start.x=j,start.y=t,start.z=i;
}else if(g[i][j][t]=='E'){
en.x=j,en.y=t,en.z=i;
}
}
}
}
if(bfs()==-1) cout<<"Trapped!"<<endl;
else cout<<"Escaped in "<<d[en.z][en.x][en.y]<<" minute(s)."<<endl;
}
return 0;
}