题目链接 https://cn.vjudge.net/problem/POJ-2251
【思路】
三维空间里的最短路,同样用BFS求解,由4个方向变成6个方向
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int dx[6]={0,0,1,0,0,-1};
const int dy[6]={0,1,0,0,-1,0};
const int dz[6]={1,0,0,-1,0,0};
const int maxn=33;
struct node{
int h,r,c;
node(int hh=0,int rr=0,int cc=0):h(hh),r(rr),c(cc){}
};
int z,x,y;
node st,en;
char g[maxn][maxn][maxn];
int a[maxn][maxn][maxn];
void bfs(){
memset(a,-1,sizeof(a));
queue<node> que;
que.push(st);
a[st.h][st.r][st.c]=0;
while(!que.empty()){
node tmp=que.front();
que.pop();
for(int k=0;k<6;++k){
int h=tmp.h+dz[k];
int r=tmp.r+dx[k];
int c=tmp.c+dy[k];
if(h<0 || h>=z) continue;
if(r<0 || r>=x) continue;
if(c<0 || c>=y) continue;
if(g[h][r][c]=='#') continue;
if(a[h][r][c]!=-1) continue;
a[h][r][c]=a[tmp.h][tmp.r][tmp.c]+1;
que.push(node(h,r,c));
}
}
}
int main(){
while(scanf("%d%d%d",&z,&x,&y)==3){
if(0==z && 0==x && 0==y) break;
for(int h=0;h<z;++h)
for(int r=0;r<x;++r)
scanf("%s",g[h][r]);
for(int h=0;h<z;++h){
for(int r=0;r<x;++r){
for(int c=0;c<y;++c){
if(g[h][r][c]=='S') st=node(h,r,c);
else if(g[h][r][c]=='E') en=node(h,r,c);
}
}
}
bfs();
if(a[en.h][en.r][en.c]==-1) puts("Trapped!");
else printf("Escaped in %d minute(s).\n",a[en.h][en.r][en.c]);
}
return 0;
}