C++
$\color{gold}{— > 蓝桥杯辅导课题解}$
思路:
BFS
$1、由于要求最短时间,用BFS(BFS:适用于求 ”最短“ 问题,比如 :最短路,最短时间等等)$
$关于$$\color{red}{BFS}$
$2、根据题目,三维迷宫,故建立三维矩阵进行BFS,由起点出发,向上下左右前后6个方向扩展,$
$直至到达终点即可(同时要注意:越界,障碍物,之前走过等情况)$
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 110;
struct Point {
int x, y, z;
};
int l, r, c;
char g[N][N][N];
Point q[N * N * N];
int dist[N][N][N];
int dx[] = {1, -1, 0, 0, 0, 0};
int dy[] = {0, 0, 1, -1, 0, 0};
int dz[] = {0, 0, 0, 0, 1, -1};
int bfs(Point start, Point end) {
int hh = 0, tt = 0;
q[0] = start;
memset(dist, -1, sizeof dist); // 将所有距离初始化为-1,表示未被搜过
dist[start.x][start.y][start.z] = 0;
while (hh <= tt) {
auto t = q[hh ++]; // 每次取出队头
for (int i = 0; i < 6; i ++) { // 6个方向
int x = t.x + dx[i], y = t.y + dy[i], z = t.z + dz[i];
if (x < 0 || x >= l || y < 0 || y >= r || z < 0 || z >= c) continue; // 越界
if (g[x][y][z] == '#') continue; // 障碍物
if (dist[x][y][z] != -1) continue; // 之前走过
dist[x][y][z] = dist[t.x][t.y][t.z] + 1; // 更新距离
if (x == end.x && y == end.y && z == end.z) return dist[x][y][z];
q[ ++ tt] = {x, y, z}; // 把当前点入队
}
}
return -1;
}
int main() {
while (cin >> l >> r >> c, l || r || c) {
Point start, end; // 起点和终点
for (int i = 0; i < l; i ++)
for (int j = 0; j < r; j ++) {
cin >> g[i][j];
for (int k = 0; k < c; k ++) { // 找起点和终点
char c = g[i][j][k];
if (c == 'S') start = {i, j, k};
else if (c == 'E') end = {i, j, k};
}
}
int distance = bfs(start, end);
if (distance == -1) puts("Trapped!");
else printf("Escaped in %d minute(s).\n", distance);
}
return 0;
}