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!
思路:
这是一个三维空间,每遍历到一个结点都往6个不同的方向进行bfs,在bfs的同时统计步数。如果在队空之前找到出口,那么跳出循环并输出其步数对应的时间;如果队列都空了还没有找到出口就输出Trapped。
上AC代码:
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
char m[32][32][32];
int dp[32][32][32];
int L,R,C;
typedef struct
{
int l;
int x;
int y;
}Pos;
int main()
{
while(~scanf("%d%d%d",&L,&R,&C))
{
queue<Pos> step;
//读取输入
int i,j,k;
if(L==0&&R==0&&C==0)
break;
for(i=0;i<L;i++)
{
for(j=0;j<R;j++)
{
scanf("%s",m[i][j]);
}
getchar();
}
//读取输入完成
memset(dp,0,sizeof(dp));
bool flag=false;
//寻找入口
for(i=0;i<L;i++)
{
for(j=0;j<R;j++)
{
for(k=0;k<C;k++)
{
if(m[i][j][k]=='S')
{
Pos t;
t.l=i;
t.x=j;
t.y=k;
step.push(t);
dp[i][j][k]=1;
flag=true;
break;
}
}
if(flag)
break;
}
if(flag)
break;
}
int p1,p2,p3;
//寻找入口完毕
flag=false;
while(!step.empty())
{
Pos t1=step.front();
step.pop();
if(m[t1.l][t1.x][t1.y]=='E')
{
p1=t1.l;
p2=t1.x;
p3=t1.y;
flag=true;
break;
}
for(i=-1;i<=1;i++)
{
if(t1.l+i<0||t1.l+i>=L)
continue;
for(j=-1;j<=1;j++)
{
if(t1.x+j<0||t1.x+j>=R)
continue;
for(k=-1;k<=1;k++)
{
if(t1.y+k<0||t1.y+k>=C)
continue;
if(((i==0&&j==0)||(i==0&&k==0)||(j==0&&k==0))&&dp[t1.l+i][t1.x+j][t1.y+k]==0&&(m[t1.l+i][t1.x+j][t1.y+k]=='.'||m[t1.l+i][t1.x+j][t1.y+k]=='E'))
{
Pos t2;
t2.l=t1.l+i;
t2.x=t1.x+j;
t2.y=t1.y+k;
dp[t2.l][t2.x][t2.y]=dp[t1.l][t1.x][t1.y]+1;
step.push(t2);
}
}
}
}
}
if(flag)
{
printf("Escaped in %d minute(s).\n",dp[p1][p2][p3]-1);
}
else
{
printf("Trapped!\n");
}
}
return 0;
}