B - Dungeon Master POJ - 2251
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!
思路:很经典的三维bfs,注意一点不用管xyz的坐标系怎么建立,直接三个for循环i j k 对应下来就行。
代码:
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef struct node {
int x,y,z;
int step;
} ty;
char a[33][33][33];
int via[33][33][33];
int n,m,l;
ty t,d;
int bfs( int a1, int a2, int a3 )
{
int next[6][3] = {
{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}
};
queue <ty> Q;
Q.empty();
t.x = a1; t.y = a2; t.z = a3; t.step = 0;
Q.push(t);
via[a1][a2][a3] = 1;
while ( !Q.empty() ) {
t = Q.front();
Q.pop(); // 此处容易漏写
if ( a[t.x][t.y][t.z]=='S' ) {
return t.step;
}
for ( int i=0; i<6; i++ ) {
d.x = t.x + next[i][0];
d.y = t.y + next[i][1];
d.z = t.z + next[i][2];
d.step = t.step + 1;
if ( d.x>=n||d.y>=m||d.z>=l || d.x<0||d.y<0||d.z<0 ) { // 不要怕麻烦,记得判断
continue ;
}
if ( via[d.x][d.y][d.z]==0 && a[d.x][d.y][d.z]!='#' ) {
via[d.x][d.y][d.z] = 1;
Q.push(d);
}
}
}
return -1;
}
int main()
{
int i,j,k;
int a1,a2,a3;
while ( cin>>n>>m>>l ) {
if ( n==0&&m==0&&l==0 ) {
break;
}
for ( i=0; i<n; i++ ) {
for ( j=0; j<m; j++ ) {
for ( k=0; k<l; k++ ) {
cin >> a[i][j][k];
if ( a[i][j][k]=='E' ) {
a1 = i;
a2 = j;
a3 = k;
}
}
}
}
memset(via,0,sizeof(via));
int isp = bfs(a1,a2,a3);
if ( isp==-1 ) {
cout << "Trapped!" << endl;
}
else {
cout << "Escaped in " << isp << " minute(s)." << endl;
}
}
return 0;
}