简单三维bfs找最短距离
#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
using namespace std;
int dx[6]={-1,1,0,0,0,0};
int dy[6]={0,0,-1,1,0,0};
int dz[6]={0,0,0,0,1,-1};
char str[100][100][100];
int step[100][100][100];
int L,R,C,res;
struct node {
int l,r,c;
};
node st,en;
int bfs(){
res = 0;
queue<node> Q;
Q.push(st);
while(!Q.empty()){
node u = Q.front();Q.pop();
if(u.l == en.l && u.r==en.r && u.c == en.c) {
res = step[u.l][u.r][u.c] ;
return 1;
}
for(int i = 0;i<6;i++){
int nx = u.l+dx[i],ny = u.r+dy[i],nz= u.c+dz[i];
if(0<=nx&&nx<L &&0<=ny && ny<R &&0<=nz && nz < C
&&step[nx][ny][nz] == -1 &&str[nx][ny][nz] !='#'){
step[nx][ny][nz] = step[u.l][u.r][u.c] + 1;
Q.push(node{nx,ny,nz});
}
}
}
return 0;
}
int main(){
while(scanf("%d%d%d",&L,&R,&C) && L && R && C){
memset(step,-1,sizeof(step));
for(int i = 0;i<L ;i++)
for(int j = 0;j < R;j++)
for(int k = 0;k<C;k++){
cin>>str[i][j][k];
if(str[i][j][k] == 'S') st.l = i,st.r= j,st.c = k,step[i][j][k] = 0;
else if(str[i][j][k] == 'E') en.l = i,en.r = j,en.c = k;
}
if(bfs()) printf("Escaped in %d minute(s).\n",res);
else printf("Trapped!\n") ;
}
return 0;
}