問題描述
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;
}