bfs搜索一遍最短时间久出来了,只不过是变成了三维而已。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef struct{
int x,y,z;
}Point;
int l,r,c;
const int N=105;
char g[N][N][N];
int dist[N][N][N];
int bfs(Point start,Point end){
memset(dist,-1,sizeof dist);
dist[start.x][start.y][start.z]=0;
queue<Point> Q;
Q.push(start);
Point t;
int dx[6]={0,0,0,0,1,-1};
int dy[6]={0,0,1,-1,0,0};
int dz[6]={1,-1,0,0,0,0};
while(Q.size()){
t=Q.front();Q.pop();
for(int i=0;i<6;i++){// x l;y r ;z c
int x=t.x+dx[i],y=t.y+dy[i],z=t.z+dz[i];
if(x<0||x>=l||y<0||y>=r||z<0||z>=c)continue;
if(dist[x][y][z]!=-1)continue;
if(g[x][y][z]=='#')continue;
dist[x][y][z]=dist[t.x][t.y][t.z]+1;
if(end.x==x&&end.y==y&&end.z==z)return dist[x][y][z];
//一开始上面这两句的顺序写反了!!!
Q.push({x,y,z});
}
}
return -1;
}
int main()
{
while(cin>>l>>r>>c,l||r||c){
Point start,end;
for(int i=0;i<l;i++){
for(int j=0;j<r;j++){
cin>>g[i][j];//读入第i层 第j行
for(int k = 0 ;k < c; k++ ){
char c = g[i][j][k];
if(c == 'S') start = {i,j,k};
if(c == 'E') end = {i,j,k};
}
}
}
//cout<<"!"<<start.x<<" "<<start.y<<" "<<start.z<<"\n";
//cout<<"!"<<end.x<<" "<<end.y<<" "<<end.z<<"\n";
int distance=bfs(start,end);
if(distance==-1)printf("Trapped!\n");
else printf("Escaped in %d minute(s).\n",distance);
}
return 0;
}