一、题目链接
二、题目分析
(一)算法标签
BFS
(二)解题思路
BFS框架见 https://blog.csdn.net/Derrickhang/article/details/123694440
详细了解搜索类题目(DFS、BFS),请移步DFS BFS 搜索题目归纳
三、AC代码
解法一:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 110;
int dx[6] = {-1, 0, 1, 0, 0, 0}, dy[6] = {0, 1, 0, -1, 0, 0}, dz[6] = {0, 0, 0, 0, 1, -1};
int l, n, m;
char g[N][N][N];
int dist[N][N][N];
struct Point {
int x, y, z;
};
int bfs(int x, int y, int z)
{
dist[x][y][z] = 0;
Point p = {x, y, z};
queue<Point> q;
q.push(p);
while (!q.empty())
{
auto t = q.front();
q.pop();
for (int i = 0; i < 6; i ++ )
{
int a = t.x + dx[i], b = t.y + dy[i], c = t.z + dz[i];
if (a < 0 || a >= l || b < 0 || b >= n || c < 0 || c >= m) continue;
if (g[a][b][c] == 'E') return dist[t.x][t.y][t.z] + 1;
if (dist[a][b][c] == -1 && g[a][b][c] == '.')
{
dist[a][b][c] = dist[t.x][t.y][t.z] + 1;
q.push({a, b, c});
}
}
}
return -1;
}
int main()
{
while (cin >> l >> n >> m, l || n || m)
{
for (int i = 0; i < l; i ++ )
for (int j = 0; j < n; j ++ )
scanf("%s", g[i][j]);
int x, y, z;
for (int i = 0; i < l; i ++ )
for (int j = 0; j < n; j ++ )
for (int k = 0; k < m; k ++ )
{
if (g[i][j][k] == 'S')
{
x = i, y = j, z = k;
break;
}
}
memset(dist, -1, sizeof dist);
int res = bfs(x, y, z);
if (res == -1) puts("Trapped!");
else printf("Escaped in %d minute(s).\n", res);
}
return 0;
}