B - Dungeon Master
题目:
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<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char a[35][35][35];
int vis[35][35][35],xx,yy,zz,step = 0;
int direction[6][3] = {{0,1,0},{0,0,1},{0,-1,0},{0,0,-1},{1,0,0},{-1,0,0}};
int L,R,C;
struct point
{
int x,y,z;
int step;
};
void bfs()
{
point point1;
point1.x = xx;
point1.y = yy;
point1.z = zz;
point1.step = 0;
queue<point> q;
q.push(point1);
vis[xx][yy][zz] = 1;
while(!q.empty())
{
point head = q.front();
q.pop();
if(a[head.x][head.y][head.z] == 'E')
{
cout << "Escaped in " << head.step << " minute(s)." << endl;
return;
}
for(int k = 0;k < 6;k++)
{
int dx = head.x + direction[k][0];
int dy = head.y + direction[k][1];
int dz = head.z + direction[k][2];
if(vis[dx][dy][dz] == 0 && dx >= 0 && dx < L && dy >= 0 && dy < R && dz >= 0 && dz < C && a[dx][dy][dz] != '#')
{
point point2;
point2.x = dx;
point2.y = dy;
point2.z = dz;
point2.step = head.step + 1;
vis[dx][dy][dz] = 1;
q.push(point2);
}
}
}
cout << "Trapped!" << endl;
}
int main()
{
while(cin >> L >> R >> C && L && R && C)
{
for(int i = 0;i < L;i++)
{
for(int j = 0;j < R;j++)
{
for(int k = 0;k < C;k++)
{
cin >> a[i][j][k];
if(a[i][j][k] == 'S')
{
xx = i;
yy = j;
zz = k;
}
}
}
}
memset(vis,0,sizeof(vis));
bfs();
}
return 0;
}
这道题要求到达终点的最短路径,所以这是一道BFS题,不过这道题选取的方向有6种,除了前后左右之外还可以往上,往下走。每走一步都要步数加一直到遇到出口,打印已走步数随后返回。
如果队列为空时都没找到出口,那么就打印Trapped!(证明此时没有通往出口的路)