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!
题意:
S为起点,E为终点,计算从S走到E需要的时间?#为岩石不可走,. 可走
思路:
三维BFS 模板题
可以将这个图看作是一个有L层的楼,有六个方向,即上下左右前后,然后进行搜索即可。
代码:
#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
int dir[6][3]={0,0,1,0,0,-1,-1,0,0,1,0,0,0,1,0,0,-1,0};
int book[42][42][42];
char mp[42][42][42];
int l,r,c;
int sx,sy,sz,ex,ey,ez;
struct node
{
int x,y,z,s;
}u,v;
int bfs()
{
queue<node>q;
u.x=sx;
u.y=sy;
u.z=sz;
u.s=0;
book[sx][sy][sz]=1;
q.push(u);
while(!q.empty())
{
u=q.front();
q.pop();
if(u.x==ex&&u.y==ey&&u.z==ez)
return u.s;
for(int i=0;i<6;i++)
{
v.x=u.x+dir[i][0];
v.y=u.y+dir[i][1];
v.z=u.z+dir[i][2];
if(v.x>=0&&v.x<l&&v.y>=0&&v.y<r&&v.z>=0&&v.z<c&&mp[v.x][v.y][v.z]!='#'&&!book[v.x][v.y][v.z])
{
book[v.x][v.y][v.z]=1;
v.s=u.s+1;
q.push(v);
}
}
}
return 0;
}
int main()
{
while(~scanf("%d %d %d",&l,&r,&c)&&l+r+c)
{
memset(book,0,sizeof(book));
for(int i=0;i<l;i++)
{
for(int j=0;j<r;j++)
{
scanf("%s",mp[i][j]);
for(int k=0;k<c;k++)
{
if(mp[i][j][k]=='S')
{
sx=i;
sy=j;
sz=k;
}
else if(mp[i][j][k]=='E')
{
ex=i;
ey=j;
ez=k;
}
}
}
}
int ans;
ans=bfs();
if(ans)
printf("Escaped in %d minute(s).\n",ans);
else
printf("Trapped!\n");
}
return 0;
}
该博客讨论了一种使用三维广度优先搜索(BFS)算法解决迷宫逃脱问题的方法。输入描述了一个由岩石和空地组成的3D迷宫,起点(S)和终点(E)标记明确。算法通过搜索所有可能的路径来确定最短的逃脱时间。如果找到出口,则输出逃脱所需的时间,否则输出被困信息。示例展示了不同迷宫情况的输入和输出,包括可行和不可行的逃脱路径。
470

被折叠的 条评论
为什么被折叠?



