题目大意:3D迷宫,’#‘为障碍物,’.‘为可行,’S‘为起点,’E‘为终点,求最短路径。

解题思路:bfs与迷宫问题类似,只是多一维,起点,终点坐标自己求一下。标记数组依然是步数数组。只要不混了,没什么难点。

ac代码:

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct node{
int x;
int y;
int z;
};
queue <node> qu;
int dx[6] = {0, 0, 0, 0, -1, 1};
int dy[6] = {0, 0, -1, 1, 0, 0};
int dz[6] = {-1, 1, 0, 0, 0, 0};
int vis[100][100][100], n, m, p, ex[6], temp;
char a[100][100][100];
void search()
{
memset(vis, -1, sizeof(vis));
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
for (int k=0; k<p; k++)
if (a[i][j][k] == 'S')
ex[0] = i, ex[1] = j, ex[2] = k;
else if (a[i][j][k] == 'E')
ex[3] = i, ex[4] = j, ex[5] = k;
else if (a[i][j][k] == '#')
vis[i][j][k] = 0;
}
int bfs()
{
while (!qu.empty())
qu.pop();
node no;
no.x = ex[0], no.y = ex[1], no.z = ex[2];
qu.push(no);
vis[no.x][no.y][no.z] = 0;
while (!qu.empty()){
node temp = qu.front();
qu.pop();
int X = temp.x, Y = temp.y, Z = temp.z;
if (X == ex[3] && Y == ex[4] && Z == ex[5])
return vis[X][Y][Z];
for (int i=0; i<6; i++){
int a = X + dx[i], b = Y + dy[i];
int c = Z + dz[i];
if (a >=0 && a < n && b >= 0 &&
b < m && c >= 0 && c < p && vis[a][b][c] == -1){
no.x = a, no.y = b, no.z = c;
qu.push(no);
vis[a][b][c] = vis[X][Y][Z] + 1;
}
}
}
return 0;
}
int main()
{
while (scanf("%d%d%d", &n, &m, &p)!=EOF){
if (!n && !m && !p)
break;
for (int i=0; i<n; i++){
for (int j=0; j<m; j++)
scanf("%s", a[i][j]);
getchar();
getchar();
}
search();
temp = bfs();
if (temp)
printf("Escaped in %d minute(s).\n", temp);
else
printf("Trapped!\n");
}
return 0;
}