Description - 题目描述
[NWUACM]
你被困在一个三维的空间中,现在要寻找最短路径逃生!
空间由立方体单位构成
你每次向上下前后左右移动一个单位需要一分钟
你不能对角线移动并且四周封闭
是否存在逃出生天的可能性?如果存在,则需要多少时间?
Input - 输入
输入第一行是一个数表示空间的数量。
每个空间的描述的第一行为L,R和C(皆不超过30)。
L表示空间的高度。
R和C分别表示每层空间的行与列的大小。
随后L层地牢,每层R行,每行C个字符。
每个字符表示空间的一个单元。'#'表示不可通过单元,'.'表示空白单元。你的起始位置在'S',出口为'E'。
每层空间后都有一个空行。L,R和C均为0时输入结束。
Output - 输出
每个空间对应一行输出。
如果可以逃生,则输出如下
Escaped in x minute(s).
x为最短脱离时间。
如果无法逃生,则输出如下
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搜索
AC代码:
Status | Accepted |
---|---|
Time | 63ms |
Memory | 272kB |
Length | 2074 |
Lang | C++ |
Submitted | 2019-07-08 13:44:14 |
#include<iostream>
#include<queue>
#include<cstdio>
#include<string.h>
using namespace std;
struct node{
int x;
int y;
int z;
int step;//记录当前节点所走的步数
};//节点
int dx[6] = {1, -1, 0, 0, 0, 0}, dy[6] = {0, 0, 1, -1, 0, 0}, dz[6] = {0, 0, 0, 0, 1, -1};//六个方向
int main()
{
int l,r,c;
int ex,ey,ez;//终点坐标
int sx,sy,sz;//起点坐标
char maze[31][31][31];
while(1)//多组输入
{
cin>>l>>r>>c;
node start;
if(l==0)
return 0;
for (int i = 0; i < l; i++)
{
for (int j = 0; j < r; j++)
{
for (int k = 0; k < c; k++)
{
cin >> maze[i][j][k];
if (maze[i][j][k] == 'S')
sx=i,sy=j,sz=k;
if (maze[i][j][k] == 'E')
ex = i, ey = j, ez = k;
}
}
getchar();
}
start.x=sx,start.y=sy,start.z=sz,start.step=0;
queue<node> q;
q.push(start);
int flag=0;
while(!q.empty())//很裸的BFS循环
{
node now=q.front();
q.pop();
if(now.x==ex&&now.y==ey&&now.z==ez)
{
flag=1;
cout<<"Escaped in "<<now.step<<" minute(s)."<<endl;
break;
}
for(int n=0;n<6;n++)
{
node next;
next.x=now.x+dx[n];
next.y=now.y+dy[n];
next.z=now.z+dz[n];
next.step=now.step+1;
if(next.x>=0&&next.y>=0&&next.z>=0&&next.x<l&&
next.y<r&&next.z<c&&maze[next.x][next.y][next.z]!='#')
{
maze[next.x][next.y][next.z]='#';//走过的区域用#覆盖掉
q.push(next);
}
}
}
if(flag)
continue;
else
cout<<"Trapped!"<<endl;
}
}