Dungeon Master
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!
思路:三维迷宫最短逃生路径,使用三维字符数组来存储迷宫信息,(我这里踩了个坑,把三维数组妖魔化了,认为其比二维数组要难很多,其实也就那样),输入多组测试用例首先
找到起点s,用起点s的三维坐标进行广搜,用int型三维数组判断该点是否访问过,遍历每一个点,当该点为终点E时,函数退出。要注意清空队列,初始化记录访问信息的数组。用结构体
存储迷宫信息下标。代码如下:
#include <iostream> #include <algorithm> #include <queue> #include <string.h> #define LL long long const int max_n = 33; using namespace std; int l, r, c; int dd[6][3]={1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1};//移动数组 int used[max_n][max_n][max_n];//记录访问信息数组 char mp[max_n][max_n][max_n];//迷宫信息 struct test {//迷宫下标 int x,y,z; int time;//走到某点所花费的时间 }; queue<test> q;//队列,方便进行搜索 bool judge(int x, int y,int z)//判断该点下标是否合规 { return x >= 0 && x < r&&y >= 0 && y < c&&z>=0&&z<l; } int bfs(int sz, int sx, int sy)//搜索函数 { memset(used,0,sizeof(used));//初始化记录信息数组 test a; a.x=sx,a.y=sy,a.z=sz; a.time=0; used[a.z][a.x][a.y]=1; q.push(a);//起点下标入队 while(!q.empty()) { test b=q.front();q.pop();//释放队首元素 for(int i=0;i<6;i++)//进行遍历 { test c; c.z=b.z+dd[i][0]; c.x=b.x+dd[i][1]; c.y=b.y+dd[i][2]; if(mp[c.z][c.x][c.y]!='#'&&judge(c.x,c.y,c.z)&&used[c.z][c.x][c.y]==0)//当 某点小标没有越界、能走且没有到达过时 { used[c.z][c.x][c.y]=1;//更改状态 c.time=b.time+1;//时间+1 q.push(c);//入队 if(mp[c.z][c.x][c.y]=='E'){//当到达终点时,返回 return c.time; } } } } return 0; } int main() { int sz, sx, sy;//起点下标 while (scanf("%d %d %d", &l, &r, &c) == 3) {//输入无误时 if (l == 0 && r == 0 && c == 0)break;//输入三个0结束输入 for (int t = 0; t < l; t++) { for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cin >> mp[t][i][j]; if (mp[t][i][j] == 'S')sz = t, sx = i, sy = j; } } } int su = 0; su = bfs(sz, sx, sy); if (su != 0)printf("Escaped in %d minute(s).\n", su); else printf("Trapped!\n"); while (q.size())q.pop();//清空队列 } return 0; }