原题链接
[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!
题目描述
一个三维的图(303030),求出从起点S到终点E的最短距离(有可能走不到) '.‘可以走,’#'不能走 。
思路:简单广搜,分别试探6种方式,最早满足条件的就是最短时间,需要注意三维数组第一维表示层数,在代码中使用z表示,与数学中的立体坐标系相似,还要注意提前记录起点位置,起点不一定是(0,0,0)
代码如下
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <queue>
using namespace std;
struct node
{
int x,y,z;
int step;
};
char m[35][35][35];
int l,r,c,book[35][35][35],mins;
int oper[6][3] = {
{0, 0, 1},
{0, 0, -1},
{0, -1, 0},
{0, 1, 0},
{1, 0, 0},
{-1, 0, 0}
};
node now;
void bfs()
{
int i;
queue<node> q;
book[0][0][0] = 1;
q.push(now);
while(!q.empty())
{
now = q.front();
q.pop();
if(m[now.z][now.x][now.y] == 'E')
{
printf("Escaped in %d minute(s).\n",now.step);
return;
}
for(i = 0;i < 6;i++)
{
node next;
next.x = now.x + oper[i][1];
next.y = now.y + oper[i][2];
next.z = now.z + oper[i][0];
next.step = now.step;
//符合试探条件,就入队
if(m[next.z][next.x][next.y]!='#'&&next.x>=0&&next.x<r&&next.y>=0&&next.y<c&&next.z>=0&&next.z<l&&!book[next.z][next.x][next.y])
{
book[next.z][next.x][next.y] = 1;
next.step++;
q.push(next);
}
}
}
printf("Trapped!\n");
}
int main()
{
int i,j,k;
while(~scanf("%d %d %d",&l,&r,&c) && l && r && c)
{
memset(book, 0, sizeof(book));
mins = INT_MAX;
for(i = 0;i < l;i++)
for(j = 0;j < r;j++)
{
scanf("%s",m[i][j]);
for(k = 0;k < c;k++)
{ //记录起点位置
if(m[i][j][k] == 'S')
{
now.x = j;
now.y = k;
now.z = i;
now.step = 0;
}
}
}
book[0][0][0] = 1;
bfs();
}
return 0;
}