Dungeon Master:
题目链接:https://vjudge.net/problem/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 lineTrapped!
简单翻译下题面:
一个有许多障碍物的3D的迷宫,给你起点和终点,问你是否能从起点走到终点,如果能最快要几分钟(移动一步一分钟);
分析:
显然是一道搜索的题,而对于这种求最短用时类型的题目一般都用广搜。
因为广搜的特性是一层层往外搜,遇到终止条件就结束搜索,那么这里搜索的层数就对应了题目里的最短用时。
而深搜的特性是从一个点一直往下走,直到不能走就回退找另外的路。那么在这道题里即使找到了终点,你也无法确保你找到的路是用时最短的路,所以你需要枚举所有通往终点的路再进行比较才能得出答案。
这道题并没有什么难点,可以说是模板题。
三维(六个方向)的广搜:
AC代码:
#include <cstdio>
#include <queue>
#include <string.h>
using namespace std;
int L,R,C;
char dungeon[35][35][35];
bool vis[35][35][35];
int direct[6][3]={{0,0,1},{0,0,-1},{1,0,0},{-1,0,0},{0,1,0},{0,-1,0}};
typedef struct{
int x,y,z;
int step;
}pos;
pos S; //起点
int bfs(pos start){
queue <pos> q;
q.push(start);
while(!q.empty()){
pos temp=q.front();
q.pop();
for(int i=0;i<6;i++){
pos new_pos;
new_pos.x=temp.x+direct[i][0];
new_pos.y=temp.y+direct[i][1];
new_pos.z=temp.z+direct[i][2];
new_pos.step=temp.step+1;
if(!vis[new_pos.x][new_pos.y][new_pos.z]&&new_pos.x<=L&&new_pos.x>=1&&new_pos.y<=R&&new_pos.y>=1&&new_pos.z<=C&&new_pos.z>=1&&dungeon[new_pos.x][new_pos.y][new_pos.z]!='#'){
vis[new_pos.x][new_pos.y][new_pos.z]=1;
if(dungeon[new_pos.x][new_pos.y][new_pos.z]=='E')
return new_pos.step;
q.push(new_pos);
}
}
}
return -1;
}
int main()
{
while(~scanf("%d%d%d",&L,&R,&C)){
if(L==0&&R==0&&C==0)
break;
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++){
scanf(" %c",&dungeon[i][j][k]);
if(dungeon[i][j][k]=='S'){
S.x=i;
S.y=j;
S.z=k;
S.step=0;
}
}
}
int t=bfs(S);
if(t!=-1)
printf("Escaped in %d minute(s).\n",t);
else
printf("Trapped!\n");
}
return 0;
}