Dungeon Master
题意描述:
你被困在一个L×R×C 的三维迷宫内,每分钟你只能够往上、下、左、右、前、后这六个方向的任意一个方向走一个单位。初始时你位于 S 位置,迷宫的出口为 E 位置,迷宫中标 # 的位置无法通过,并且你也不能够走出迷宫的边界。
你是否能够走出这个迷宫?如果能,求出最少的时间。
思路解析:
看到走迷宫首先想到的就是bfs(宽度优先搜索),由于本题是三维空间走迷宫,怎么来存坐标呢,可以想到的是用struct或array来存,怎么记录通过时间呢,我们可以开辟一个三维数组 在队列出栈入栈过程中来记录距离。
AC代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <queue>
using namespace std;
const int N = 50;
char g[N][N][N];
const int dx[] = {0, 0, 0, 0, -1, 1},
dy[] = {0, 0, -1, 1, 0, 0},
dz[] = {-1, 1, 0, 0, 0, 0};
struct node {
int x, y, z;
};
int l, r, c;
queue<node>q;
int d[N][N][N];
int bfs(node st) {
while (!q.empty()) q.pop();
q.push(st);
d[st.x][st.y][st.z] = 0;
while (!q.empty()) {
node t = q.front();
q.pop();
g[t.x][t.y][t.z] = '#';
for (int i = 0; i < 6; i ++) {
int x = t.x + dx[i], y = t.y + dy[i], z = t.z + dz[i];
if (g[x][y][z] == '#') continue;
if (x < 0 || x >= l || y < 0 || y >= r || z < 0 || z >= c) continue;
d[x][y][z] = d[t.x][t.y][t.z] + 1;
if (g[x][y][z] == 'E') return d[x][y][z];
g[x][y][z] = '#';
// q.push({x,y,z});
node stt;
stt.x = x, stt.y = y, stt.z = z;
q.push(stt);
}
}
return 0;
}
int main() {
while (cin >> l >> r >> c && l && r && c) {
for (int i = 0; i < l; i ++)
for (int j = 0; j < r; j ++)
scanf("%s", g[i][j]);
node st;
for (int i = 0; i < l; i ++)
for (int j = 0; j < r; j ++)
for (int k = 0; k < c; k ++)
if (g[i][j][k] == 'S') {
//st = {i, j, k};
st.x = i, st.y = j, st.z = k;
break;
}
int res = bfs(st);
if (res) printf("Escaped in %d minute(s).\n", res);
else puts("Trapped!");
}
return 0;
}