题解:按照bfs的套路,不过多了一个三维数组,先是z轴,然后是x、y轴。
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int N = 35;
struct P {
int x, y, z;
}p;
int l, r, c, x1, y1, z1, x2, y2, z2, flag1;
char pos[N][N][N];
int vis[N][N][N];
int flag[6][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {-1, 0, 0}, {0, -1, 0}, {0, 0, -1}};
queue<P> q;
void init() {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++) {
pos[i][j][k] = '\0';
vis[i][j][k] = 0;
}
flag1 = 0;
while (!q.empty())
q.pop();
}
void bfs() {
int x0, y0, z0;
while (!q.empty()) {
for (int i = 0; i < 6; i++) {
x0 = x1 + flag[i][0];
y0 = y1 + flag[i][1];
z0 = z1 + flag[i][2];
if (x0 < 0 || x0 >= r || y0 < 0 || y0 >= c || z0 < 0 || z0 >= l)
continue;
if (vis[z0][x0][y0] == 0 && (pos[z0][x0][y0] == '.' || pos[z0][x0][y0] == 'E')) {
vis[z0][x0][y0] = vis[z1][x1][y1] + 1;
if (pos[z0][x0][y0] == 'E') {
flag1 = 1;
return;
}
p.x = x0;
p.y = y0;
p.z = z0;
q.push(p);
}
}
q.pop();
p = q.front();
x1 = p.x;
y1 = p.y;
z1 = p.z;
}
}
void found() {
for (int i = 0; i < l; i++)
for (int j = 0; j < r; j++)
for (int k = 0; k < c; k++) {
if (pos[i][j][k] == 'S') {
x1 = p.z = j;
y1 = p.x = k;
z1 = p.y = i;
q.push(p);
bfs();
continue;
}
if (pos[i][j][k] == 'E') {
x2 = j;
y2 = k;
z2 = i;
continue;
}
}
}
int main() {
while (scanf("%d%d%d", &l, &r, &c) && l) {
getchar();
init();
for (int i = 0; i < l; i++) {
for (int j = 0; j < r; j++)
scanf("%s", pos[i][j]);
getchar();
}
getchar();
found();
if (flag1 == 0)
printf("Trapped!\n");
else
printf("Escaped in %d minute(s).\n", vis[z2][x2][y2]);
init();
}
return 0;
}