Dungeon Master POJ - 2251
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<queue>
using namespace std;
char a[35][35][35];
bool vis[35][35][35];
int l,r,c;
int a1,a2,a3,b1,b2,b3;
int to[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
int ans,flag=0;
struct node{
int x,y,z;
int step;
};
bool judge(int x,int y,int z)
{
if(x<0||y<0||z<0)
{
return false;
}
if(x>=l||y>=r||z>=c)
{
return false;
}
if(a[x][y][z]=='#')
{
return false;
}
if(vis[x][y][z])
{
return false;
}
return true;
}
void bfs()
{
node cur,next;
queue<node>q;
cur.x=a1,cur.y=a2,cur.z=a3;
cur.step=0;
q.push(cur);
vis[cur.x][cur.y][cur.z]=true;
while(!q.empty())
{
cur=q.front();
q.pop();
int i,j;
if(cur.x==b1&&cur.y==b2&&cur.z==b3)
{
ans=cur.step;
flag=1;
return;
}
for(i=0;i<6;i++)
{
int nx=cur.x+to[i][0];
int ny=cur.y+to[i][1];
int nz=cur.z+to[i][2];
if(!judge(nx,ny,nz))
{
continue;
}
vis[nx][ny][nz]=true;
next.x=nx;
next.y=ny;
next.z=nz;
next.step=cur.step+1;
q.push(next);
}
}
}
int main()
{
int i,j,k;
while(cin>>l>>r>>c)
{
memset(vis,0,sizeof(vis));
memset(a,0,sizeof(a));
flag=0;
if(l==0&&r==0&&c==0)
{
break;
}
for(i=0;i<l;i++)
{
for(j=0;j<r;j++)
{
for(k=0;k<c;k++)
{
cin>>a[i][j][k];
if(a[i][j][k]=='S')
{
a1=i,a2=j,a3=k;
}
if(a[i][j][k]=='E')
{
b1=i,b2=j,b3=k;
}
}
}
}
bfs();
if(flag)
{
cout<<"Escaped in "<<ans<<" minute(s)."<<endl;
}
else
{
cout<<"Trapped!"<<endl;
}
}
return 0;
}