题意:就是一个三维最短路,求S点到E点的最短距离。一个BFS直接水过
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxm=50;
char map[maxm][maxm][maxm];
int vis[maxm][maxm][maxm];
int p,n,m;
int x1,y1,z1,x2,y2,z2;
struct node
{
int x;
int y;
int z;
int step;
}queue[maxm*maxm*maxm];
int ok;
int dir[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
int bfs()
{
struct node now,pre;
int e=0,h=1;
queue[0].x=x1;
queue[0].y=y1;
queue[0].z=z1;
queue[0].step=0;
while(e<h)
{
pre=queue[e];
if(pre.x==x2&&pre.y==y2&&pre.z==z2)
{
ok=1;
return pre.step;
}
for(int i=0;i<6;i++)
{
now.x=pre.x+dir[i][0];
now.y=pre.y+dir[i][1];
now.z=pre.z+dir[i][2];
now.step=pre.step+1;
if(now.x>=0&&now.x<p&&now.y>=0&&now.y<n&&now.z>=0&&now.z<m&&!vis[now.x][now.y][now.z]&&map[now.x][now.y][now.z]!='#')
{
vis[now.x][now.y][now.z]=1;
queue[h++]=now;
}
}
e++;
}
return -1;
}
int main()
{
while(scanf("%d%d%d",&p,&n,&m)!=EOF&&(n||m||p))
{
ok=0;
memset(vis,0,sizeof(vis));
for(int i=0;i<p;i++)
{
for(int j=0;j<n;j++)
{
scanf("%s",map[i][j]);
for(int k=0;k<m;k++)
{
if(map[i][j][k]=='S')
{
x1=i;
y1=j;
z1=k;
}
if(map[i][j][k]=='E')
{
x2=i;
y2=j;
z2=k;
}
}
}
}
int s=bfs();
if(ok&&s!=-1)
{
printf("Escaped in %d minute(s).\n",s);
}
else
{
printf("Trapped!\n");
}
}
return 0;
}