您的位置:首页 > 其它

POJ 2251 Dungeon Master(bfs)

2015-07-09 11:30 405 查看
Description

给出一三维空间的地牢,要求求出由字符’S’到字符’E’的最短路径,移动方向可以是上,下,左,右,前,后,六个方向,每移动一次就耗费一分钟,要求输出最快的走出时间

Input

多组用例,每组用例第一行为三个整数表示迷宫的高度Z,宽度Y和长度X,之后为Z个Y*X矩阵,每个矩阵间有一空行,每组用例间有一空行,以Z=Y=X=0结束输入

Output

对于每组用例,输出最快的走出时间,如果走不出去则输出Trapped!

Sample Input

3 4 5

S….

.###.

.##..

###.#

#####

#####

##.##

##…

#####

#####

#.###

####E

1 3 3

S##

#E#

###

0 0 0

Sample Output

Escaped in 11 minute(s).

Trapped!

Solution

三维迷宫,简单bfs

Code

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
#include<functional>
using namespace std;
#define maxn 31
#define INF 10000000
struct P
{
int x,y,z;
};
int dis[maxn][maxn][maxn];
char map[maxn][maxn][maxn];
int X,Y,Z;
P s,e;
queue <P> que;
int dx[6]={0,0,1,-1,0,0};
int dy[6]={1,-1,0,0,0,0};
int dz[6]={0,0,0,0,1,-1};
int bfs()
{
for(int z=1;z<=Z;z++)
for(int y=1;y<=Y;y++)
for(int x=1;x<=X;x++)
dis[z][y][x]=INF;//初始化
que.push(s);//进队
dis[s.z][s.y][s.x]=0;
while(que.size())
{
P p=que.front();//出列
que.pop();
if(p.x==e.x&&p.y==e.y&&p.z==e.z)//到达终点
break;
for(int i=0;i<6;i++)//六个方向枚举
{
int xx=p.x+dx[i],yy=p.y+dy[i],zz=p.z+dz[i];
if(xx>0&&yy>0&&zz>0&&xx<=X&&yy<=Y&&zz<=Z&&dis[zz][yy][xx]==INF&&map[zz][yy][xx]!='#')
{
P temp;
temp.x=xx;
temp.y=yy;
temp.z=zz;
que.push(temp);//进队
dis[zz][yy][xx]=dis[p.z][p.y][p.x]+1;//步数加一
}
}
}
return dis[e.z][e.y][e.x];
}

int main()
{
while(scanf("%d %d %d\n",&Z,&Y,&X))
{
if(Z==0)//输入结束条件
break;
while(!que.empty())//清空队列
que.pop();
memset(map,'.',sizeof(map));//初始化
for(int z=1;z<=Z;z++)
{
for(int y=1;y<=Y;y++)
{
for(int x=1;x<=X;x++)
{
scanf("%c",&map[z][y][x]);
if(map[z][y][x]=='S')//起点坐标
s.x=x,s.y=y,s.z=z;
else if(map[z][y][x]=='E')//终点坐标
e.x=x,e.y=y,e.z=z;
}
getchar();//控制输入
}
getchar();//控制输入
}
int ans=bfs();
if(ans==INF)//走不出去
printf("Trapped!\n");
else//可以走出去
printf("Escaped in %d minute(s).\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: