思路
以前做过几道二维坐标的BFS这道题是三维的道理一样,别忘加一个vis数组表示是否遍历过,用搜索最短路径的基本思路做就行了。
代码
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int maxn = 35;
char map[maxn][maxn][maxn];
bool vis[maxn][maxn][maxn];
int L, R, C;
int bx, by, bz; //起点的坐标
int ex, ey, ez; //终点的坐标
struct node {
int x, y, z;
int step;
};
int dir[][3] = {{1, 0, 0}, {-1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}};
bool check(int x, int y, int z) {
return (x >= 0 && x < C && y >= 0 && y < R && z >= 0 && z < L && !vis[z][y][x] && map[z][y][x] != '#');
}
int bfs() {
queue<node> qu;
memset(vis, false, sizeof(vis));
node v, t, next;
t.x = bx;
t.y = by;
t.z = bz;
t.step = 0;
qu.push(t);
while(!qu.empty()) {
v = qu.front(); qu.pop();
for(int i = 0; i < 6; i++) {
next.x = v.x + dir[i][0];
next.y = v.y + dir[i][1];
next.z = v.z + dir[i][2];
next.step = v.step + 1;
if (ex == next.x && ey == next.y && ez == next.z) {
return next.step;
}
if (check(next.x, next.y, next.z)) {
vis[next.z][next.y][next.x] = true;
qu.push(next);
}
}
}
return -1;
}
int main() {
//freopen("input.txt", "r", stdin);
while(scanf("%d%d%d", &L, &R, &C) != EOF && L) {
for(int l = 0; l < L; l++) {
for(int r = 0; r < R; r++) {
scanf("%s", map[l][r]);
for(int c = 0; c < C; c++) {
if (map[l][r][c] == 'S') {
bx = c;
by = r;
bz = l;
}
else if (map[l][r][c] == 'E') {
ex = c;
ey = r;
ez = l;
}
}
}
}
int ans;
if ((ans = bfs()) != -1) printf("Escaped in %d minute(s).\n", ans);
else printf("Trapped!\n");
}
return 0;
}