题目连接: 胜利大逃亡
解题思路:
三维BFS, 挺简单的. 但是我找了一个多小时BUG, 以前做的bfs都不涉及能跑到出口, 但是出口居然 不!能!走! 的情况, 我真的是裂开了.
AC代码:
#include <cstdio>
#include <queue>
using namespace std;
int mp[55][55][55];
struct node {
int x, y, z;
int step;
node(int x, int y, int z, int step = 0): x(x), y(y), z(z), step(step) {}
};
int a, b, c, t;
int fx[][3] = { { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } };
void bfs() {
queue<node> q;
node temp(1, 1, 1, 0); //没有C++11 TwT
q.push(temp); mp[1][1][1] = 1;
while (!q.empty()) {
node op = q.front(); q.pop();
if (op.step + 1 > t) continue;
for (int i = 0; i < 6; i++) {
int dx = op.x + fx[i][0];
int dy = op.y + fx[i][1];
int dz = op.z + fx[i][2];
if (dx == a && dy == b && dz == c && !mp[dx][dy][dz] ) //写博客就是为了记录这里, 要判断终点能不能走!!!!!!
{ printf("%d\n", op.step + 1); return; }
if (dx <= 0 || dx > a || dy <= 0 || dy > b || dz <= 0 || dz > c || mp[dx][dy][dz]) continue;
node temp(dx, dy, dz, op.step + 1);
q.push(temp);
mp[dx][dy][dz] = 1;
}
}
printf("-1\n");
}
int main()
{
int T; scanf("%d", &T);
while (T--) {
scanf("%d %d %d %d", &a, &b, &c, &t);
for (int i = 1; i <= a; ++i) {
for (int j = 1; j <= b; ++j) {
for (int k = 1; k <= c; ++k) {
scanf("%d", &mp[i][j][k]);
}
}
}
bfs();
}
return 0;
}
下次一定会想着判断的, 下次一定.