寒假集训 最简单的bfs模板题Dungeon Master题解

其实说是模板题,作为一个萌新我还是改了好久好久,问了好几次大佬,去晚上参考别人的代码好不容易A了,人生第一道bfs题
开心开心。
Submit Status

Description

You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides.

Is an escape possible? If yes, how long will it take?

Input

The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size).
L is the number of levels making up the dungeon.
R and C are the number of rows and columns making up the plan of each level.
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a '#' and empty cells are represented by a '.'. Your starting position is indicated by 'S' and the exit by the letter 'E'. There's a single blank line after each level. Input is terminated by three zeroes for L, R and C.

Output

Each maze generates one line of output. If it is possible to reach the exit, print a line of the form
Escaped in x minute(s).

where x is replaced by the shortest time it takes to escape.
If it is not possible to escape, print the line
Trapped!

Sample Input

3 4 5
S....
.###.
.##..
###.#

#####
#####
##.##
##...

#####
#####
#.###
####E

1 3 3
S##
#E#
###

0 0 0

Sample Output

Escaped in 11 minute(s).
Trapped!
题目很简单,就是让从起始点走到最后,这个不需要考虑是否为最短路径,因为只要能走到就一定是最短路径。那么上代码
 
      
#include #include #include #include
using namespace std; //#define N 32 struct position {     int x,y,z,step; };
char mmap[N][N][N]; int xs,ys,zs; int l,r,c;
int dx[6]= {0, 0,1,-1,0, 0}; int dy[6]= {0, 0,0, 0,1,-1}; int dz[6]= {1,-1,0, 0,0, 0}; int bfs(position now) {     queue qq;     qq.push(now);     while(qq.size())     {         now=qq.front();         qq.pop();         if(mmap[now.z][now.x][now.y]=='E')             return now.step;         for(int i=0; i<6; i++)         {             position nex=now;             nex.x+=dx[i];             nex.y+=dy[i];             nex.z+=dz[i];             nex.step++;             if(nex.x>=0&&nex.y>=0&&nex.z>=0&&nex.x
其实我的里面有个不好的地方,我没开visit数组,开了就不需要重复去判断了,因为我每走一步就会把之前的点变成#,这就导致我的E点可能会被变成#,所以要多进行一次判断。但其实如果开了vis数组记录这个点走没走过,就不需要再多判断一次了。但是懒得改了!啊好懒,下一道bfs的题马上就会来了,下次尽量用上vis数组。

你可能感兴趣的:(题解)