嘛 挺进地牢OI版?
这题挺有趣的,并不是传统意义上的BFS
而是给了你一个分层的3D图,让你在这个图上找出一条最短路
跟传统BFS相比 我们要增加两个方向:上和下
我们所在的层数就是对应Z轴的坐标
剩下就是一个三维的BFS了
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int dx[7] = {0, 0, 0, 0, 0, 1, -1};
const int dy[7] = {0, 0, 0, 1, -1, 0, 0};
const int dz[7] = {0, 1, -1, 0, 0, 0, 0};
char map[40][40][40];
bool vis[40][40][40];
int stx, sty, stz, edx, edy, edz, k, n, m;
struct data {
int x, y, z;
int step;
};
inline bool check(int x, int y, int z) {
if(x < 0 || y < 0 || z < 0 || x >= k || y >= n || z >= m) return false;
else if(map[x][y][z] == '#' || vis[x][y][z]) return false;
return true;
}
inline int bfs() {
queue<data> Q;
data now, next;
now.x = stx, now.y = sty, now.z = stz, now.step = 0;
vis[stx][sty][stz] = true; Q.push(now);
while(!Q.empty()) {
now = Q.front(); Q.pop();
if(now.x == edx && now.y == edy && now.z == edz) return now.step;
for(int i = 1; i <= 6; ++i) {
next.x = now.x + dx[i];
next.y = now.y + dy[i];
next.z = now.z + dz[i];
next.step = now.step + 1;
if(!check(next.x, next.y, next.z)) continue;
vis[next.x][next.y][next.z] = true;
Q.push(next);
}
}
return 0;
}
int main() {
while(scanf("%d%d%d", &k, &n, &m) && (n || m || k)) {
memset(vis, false, sizeof(vis));
for(int i = 0; i < k; ++i) for(int j = 0; j < n; ++j) {
scanf("%s", map[i][j]);
for(int r = 0; r < m; ++r) {
if(map[i][j][r] == 'S') stx = i, sty = j, stz = r;
else if(map[i][j][r] == 'E') edx = i, edy = j, edz = r;
}
}
int ans = bfs();
if(ans) printf("Escaped in %d minute(s).\n", ans);
else puts("Trapped!");
}
return 0;
}