BFS ~不解释。
代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
const int MAXSIZE = 1000003;
int l, r, c, fl, fr, fc, dis[MAXSIZE];
int p1[6] = {1, -1, 0, 0, 0, 0};
int p2[6] = {0, 0, 1, -1, 0, 0};
int p3[6] = {0, 0, 0, 0, 1, -1};
char a[31][31][31];
bool vis[31][31][31];
struct Path
{
int x, y, z;
} path[MAXSIZE];
int bfs()
{
dis[1] = 0;
path[1].x = fc;
path[1].y = fr;
path[1].z = fl;
memset(vis, false, sizeof(vis));
int front = 1, rear = 2;
while(front < rear)
{
for(int i=0; i<6; i++)
{
int xx = path[front].x + p1[i];
int yy = path[front].y + p2[i];
int zz = path[front].z + p3[i];
if(xx >= 0 && xx < c
&&yy >= 0 && yy < r
&&zz >= 0 && zz < l
&&a[zz][yy][xx] != '#')
{
if(a[zz][yy][xx] == 'E')
return dis[front] + 1;
if(a[zz][yy][xx] == '.' && !vis[zz][yy][xx])
{
vis[zz][yy][xx] = true;
dis[rear] = dis[front] + 1;
path[rear].x = xx;
path[rear].y = yy;
path[rear].z = zz;
++rear;
}
}
}
++front;
}
return 0;
}
int main()
{
#ifdef test
freopen("sample.txt", "r", stdin);
#endif
int num;
while(scanf("%d%d%d", &l, &r, &c), l&&r&&c)
{
memset(a, 0, sizeof(a));
for(int i=0; i<l; i++)
{
for(int j=0; j<r; j++)
{
getchar();
for(int k=0; k<c; k++)
{
scanf("%c", &a[i][j][k]);
if(a[i][j][k] == 'S')
{
fl = i;
fr = j;
fc = k;
}
}
}
getchar();
}
num = bfs();
if(num)
printf("Escaped in %d minute(s).\n", num);
else
puts("Trapped!");
}
return 0;
}