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套路了。
具体的解题思路可以看下面的代码,不清楚题意的可以留言~
#include
#include
#include
using namespace std;
const int maxn = 35;
typedef struct{
int x,y,z,d;
} P;
int l,r,c;
int map[maxn][maxn][maxn];
int vis[maxn][maxn][maxn]; //访问数组,访问过的就不要再访问啦
int d[6][3] = {{1,0,0},{0,1,0},{-1,0,0},{0,-1,0},{0,0,1},{0,0,-1}}; //六个方向
P s,e; //起点,终点
bool bfs(){
queue<P> q;
vis[s.x][s.y][s.z] = 1;
q.push(s);
while(!q.empty()){
P p = q.front();
q.pop();
if(p.x == e.x && p.y == e.y && p.z == e.z){ //终点判定
cout<<"Escaped in "<<p.d<<" minute(s)."<<endl;
return true;
}
for(int i = 0;i < 6;i++){ //遍历六个方向
int x = p.x + d[i][0]; //新位置
int y = p.y + d[i][1];
int z = p.z + d[i][2];
int d = p.d + 1; //永远比前一步多1
if(x < 1 || x > l || y < 1 || y > r || z < 1 || z > c || !map[x][y][z] || vis[x][y][z]) //边界判定+墙判定+访问判定
continue;
vis[x][y][z] = 1; //先到的一定比后到的快啦,所以后面的再访问就没有意义了
P pp;
pp.x= x; pp.y = y; pp.z = z; pp.d = d;
q.push(pp); //新点入队
}
}
return false;
}
int main(){
cin>>l>>r>>c;
while(l && r && c){
memset(map,0,sizeof(map)); //初始化
memset(vis,0,sizeof(vis));
for(int i = 1;i <= l;i++){
for(int j = 1;j <= r;j++){
for(int k = 1;k <= c;k++){
char c;
cin>>c;
if(c == 'S'){ //处理地图,标识障碍物,取得起点和终点
s.x = i, s.y = j, s.z = k;
}else if(c == 'E'){
map[i][j][k] = 1;
e.x = i, e.y = j, e.z = k;
}else if(c == '.'){
map[i][j][k] = 1;
}
}
}
}
if(!bfs()){
cout<<"Trapped!"<<endl;
}
cin>>l>>r>>c;
}
return 0;
}