Description - 题目描述
你被困在一个3D地牢中且继续寻找最短路径逃生!地牢由立方体单位构成,立方体单位中有的会充满岩石。向上下前后左右移动一个单位需要一分钟。你不能向对角线的四个方向移动且迷宫四周环绕着许多岩石。
是否可以逃出地牢?如果可以,则需要多少时间?
Input - 输入
输入的第一行包含一个数,表示地牢的数量。
每个地牢的描述,其第一行包含三个数L,R和C(均小于等于30)。
L表示地牢的层数;R和C分别表示每层地牢的行与列的大小。
随后输入地牢的层数L,每层中包含R行,每行中包含C个字符。
每个字符表示地牢的一个单元。'#'表示岩石单元,'.'表示空白单元。你的起始位置在点'S',出口为'E'。
每层地牢的输入后都有一个空行。当L,R和C均为0时,输入结束。
Output - 输出
每个迷宫对应一行输出。
如果可以逃生,则输出如下
Escaped in x minute(s).
x为最短脱离时间。
如果无法逃生,则输出如下
Trapped!
Sample Input - 输入样例
3 4 5
S....
.###.
.##..
###.#
#####
#####
##.##
##...
#####
#####
#.###
####E
1 3 3
S##
#E#
###
0 0 0
Sample Output - 输出样例
Escaped in 11 minute(s).
Trapped!
这题肯定得用BFS,关于搜索的顺序我是先把当前所在点的位置平面能走的位置先搜索一遍,再去判断上下能不能走, 找到最先到达终点的路就是最短路。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};// 这仨就是方向数组
const int dz[] = {-1, 1};
char map[35][35][35];
int vis[35][35][35];//标记数组
int L, R, C;
using namespace std;
struct book
{
int x, y, z, step;
book() {}
book(int _x, int _y, int _z, int _step) ://构造函数 (大佬讲的这种花里胡哨的东西 我也没明白这是咋回事 功能就等同于 int xx = q.x + dx[i]; q.x = xx;)
x(_x), y(_y), z(_z), step(_step) {}
};
int bfs(int x, int y, int z)
{
queue<book> Q;
Q.push(book(x, y, z, 0));
memset(vis, 0, sizeof(vis));
while(!Q.empty())
{
book q = Q.front(); Q.pop();
if(map[q.z][q.x][q.y] == 'E') { return q.step; }//判断能否到终点
for(int i = 0; i < 4; i++)//先在同一平面内搜完能走的点
{
int ex = q.x + dx[i];
int ey = q.y + dy[i];
int ez = q.z;
int step = q.step;
if(ex >= 0 && ex < R && ey >= 0 && ey < C &&
map[ez][ex][ey] != '#' && !vis[ez][ex][ey])//判断的条件:1。不越界2.没走过3.这路能走
{
Q.push(book(ex, ey, ez, step+1));
vis[ez][ex][ey] = 1;
}
}
for(int i = 0; i < 2; i++)//搜垂直能走的点
{
int ex = q.x, ey = q.y;
int ez = q.z + dz[i];
int step = q.step;
if(ez >= 0 && ez < L && map[ez][ex][ey] != '#' && !vis[ez][ex][ey])//相同判断条件
{
Q.push(book(ex, ey, ez, step+1));
vis[ez][ex][ey] = 1;
}
}
}
return -1;
}
int main()
{
while(~scanf("%d %d %d", &L, &R, &C) && L)
{
getchar();
int x, y, z;
for(int i = 0; i < L; i++)
{
for(int j = 0; j < R; j++)
{
for(int k = 0; k < C; k++)
{
scanf("%c", &map[i][j][k]);
if(map[i][j][k] == 'S') { z = i; x = j; y = k; }//标记入口处
}
getchar();
}
getchar();
}
int step = bfs(x, y, z);
if(step == -1) printf("Trapped!\n");
else printf("Escaped in %d minute(s).\n", step);
}
return 0;
}