问题描述
zjm被困在一个三维的空间中,现在要寻找最短路径逃生!
空间由立方体单位构成。
zjm每次向上下前后左右移动一个单位需要一分钟,且zjm不能对角线移动。
空间的四周封闭。zjm的目标是走到空间的出口。
是否存在逃出生天的可能性?如果存在,则需要多少时间?
Input
输入第一行是一个数表示空间的数量。
每个空间的描述的第一行为L,R和C(皆不超过30)。
L表示空间的高度,R和C分别表示每层空间的行与列的大小。
随后L层,每层R行,每行C个字符。
每个字符表示空间的一个单元。’#‘表示不可通过单元,’.‘表示空白单元。
zjm的起始位置在’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迷宫问题模版题。
完整代码
//#pragma GCC optimize(2)
//#pragma G++ optimize(2)
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <climits>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int maxn=31;
char ch[maxn][maxn][maxn];
int l,r,c;//高度,行,列
int sx,sy,sz,ex,ey,ez;//start & end
int dis[maxn][maxn][maxn];
int dx[]={0,0,1,-1,0,0};
int dy[]={1,-1,0,0,0,0};
int dz[]={0,0,0,0,1,-1};
struct node{
node(int _x,int _y,int _z):x(_x),y(_y),z(_z){}
int x,y,z;
};
bool Is_end(const node &a){
return (a.x==ex && a.y==ey && a.z==ez);
}
bool Go_next(const node &a){
return (a.x>=1 && a.x<=r && a.y>=1 && a.y<=c && a.z>=1 && a.z<=c && ch[a.x][a.y][a.z]!='#' && dis[a.x][a.y][a.z]==INT_MAX/2);
}
int getint(){
int x=0,s=1; char ch=' ';
while(ch<'0' || ch>'9'){ ch=getchar(); if(ch=='-') s=-1;}
while(ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar();}
return x*s;
}
void output(){
printf("sx: %d sy: %d sz: %d\n",sx,sy,sz);
printf("ex: %d ey: %d ez: %d\n",ex,ey,ez);
for (int i=1; i<=l; i++){
for (int j=1; j<=r; j++){
for (int k=1; k<=c; k++){
printf("%d ",dis[j][k][i]);
}
printf("\n");
}
printf("\n");
}
}
void bfs(){
//memset(dis,INT_MAX/2,sizeof(dis));
for (int i=1; i<=l; i++)
for (int j=1; j<=r; j++)
for (int k=1; k<=c; k++)
dis[j][k][i]=INT_MAX/2;
queue<node> q;
node snode(sx,sy,sz);
q.push(snode); dis[sx][sy][sz]=0;
while(!q.empty()){
node temp_node=q.front(); q.pop();
if(Is_end(temp_node)) break;
for (int i=0; i<6; i++){
node new_node(temp_node.x+dx[i],temp_node.y+dy[i],temp_node.z+dz[i]);
if(Go_next(new_node)){
q.push(new_node);
dis[new_node.x][new_node.y][new_node.z]=dis[temp_node.x][temp_node.y][temp_node.z]+1;
}
}
}
//output();
if(dis[ex][ey][ez]!=INT_MAX/2) printf("Escaped in %d minute(s).\n",dis[ex][ey][ez]);
else printf("Trapped!\n");
}
int main(){
//ios::sync_with_stdio(false);
//cin.tie(0);
while(scanf("%d %d %d",&l,&r,&c)==3 && !(l==0 && r==0 && c==0)){
for (int i=1; i<=l; i++)
for (int j=1; j<=r; j++)
for (int k=1; k<=c; k++){
scanf(" %c",&ch[j][k][i]);
//cin>>ch[j][k][i];
if(ch[j][k][i]=='S') sx=j,sy=k,sz=i;
if(ch[j][k][i]=='E') ex=j,ey=k,ez=i;
}
bfs();
}
return 0;
}