题目:
输入样例:
3 4 5
S....
.###.
.##..
###.#
#####
#####
##.##
##...
#####
#####
#.###
####E
1 3 3
S##
#E#
###
0 0 0
输出样例:
Escaped in 11 minute(s).
Trapped!
思路:bfs(三维)
代码:
#include<bits/stdc++.h>
using namespace std;
const int N=110;
char p[N][N][N];//三维空间某位置上的字符
int dist[N][N][N];//距离起点的距离
struct Point//坐标
{
int x,y,z;
};
int L,R,C;
int bfs(Point Start,Point End)
{
queue<Point>q;
memset(dist,-1,sizeof dist);
q.push(Start);
dist[Start.x][Start.y][Start.z]=0;
while(q.size()){
Point t=q.front();
q.pop();
int dx[6]={1,-1,0,0,0,0},dy[6]={0,0,1,-1,0,0},dz[6]={0,0,0,0,1,-1};
for(int i=0;i<6;i++){
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(p[x][y][z]=='#')continue;
if(dist[x][y][z]!=-1)continue;
dist[x][y][z]=dist[t.x][t.y][t.z]+1;
if(x==End.x&&y==End.y&&z==End.z)return dist[x][y][z];
q.push({x,y,z});
}
}
return -1;
}
int main()
{
cin>>L>>R>>C;
Point Start,End;
while(scanf("%d%d%d",&L,&R,&C),L||R||C)//输入000停止
{
for(int i=0;i<L;i++){
for(int j=0;j<R;j++){
scanf("%s",&p[i][j]);//按行输入
for(int k=0;k<C;k++){
if(p[i][j][k]=='S')Start={i,j,k};
else if(p[i][j][k]=='E')End={i,j,k};
}
}
}
int distance=bfs(Start,End);
if(distance==-1)printf("Trapped!\n");
else printf("Escaped in %d minute(s).\n",distance);
}
return 0;
}