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….
.###.
..##..
###.######
#####
##.##
##…#####
#####
#.###
####E1 3 3
S##
#E#
###0 0 0
Sample Output
Escaped in 11 minute(s).
Trapped!
这题就是一个简单的bfs,只是变成了三维的实现,平时不常见仅此而已。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>
using namespace std;
const int mm=35;
int dx[]={0,0,0,0,1,0,-1};
int dy[]={0,0,0,1,0,-1,0};
int dz[]={0,1,-1,0,0,0,0};
struct dqs
{
int x,y,z,step;
};
char map[mm][mm][mm];
bool vis[mm][mm][mm];
int sx,sy,sz;
queue<dqs>q;
int l,r,c;
bool check(int x,int y,int z)
{
if(x>=1&&x<=l&&y>=1&&y<=r&&z>=1&&z<=c&&!vis[x][y][z]&&map[x][y][z]!='#')
return true;
return false;
}
void bfs()
{
dqs begin;
begin.x=sx,begin.y=sy,begin.z=sz;
vis[sx][sy][sz]=1;
begin.step=0;
q.push(begin);
while(!q.empty())
{
dqs head=q.front();
q.pop();
dqs now;
for(int i=1;i<=6;i++)
{
now.x=head.x+dx[i];
now.y=head.y+dy[i];
now.z=head.z+dz[i];
if(check(now.x,now.y,now.z))
{
now.step=head.step+1;
vis[now.x][now.y][now.z]=1;
if(map[now.x][now.y][now.z]=='E')
{
printf("Escaped in %d minute(s).\n",now.step);
return;
}
q.push(now);
}
}
}
printf("Trapped!\n");
return;
}
int main()
{
while(true)
{
scanf("%d%d%d",&l,&r,&c);
if(l==0&&r==0&&c==0)
break;
while(!q.empty())
q.pop();
memset(vis,0,sizeof(vis));
memset(map,0,sizeof(map));
for(int i=1;i<=l;i++)
for(int j=1;j<=r;j++)
for(int k=1;k<=c;k++)
{
cin>>map[i][j][k];
if(map[i][j][k]=='S')
sx=i,sy=j,sz=k;
}
bfs();
}
return 0;
}