您的位置:首页 > 其它

POJ 2251 Dungeon Master (三维BFS)

2018-01-18 10:48 453 查看
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!

和二维广搜相比  改变方向数组即可

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<algorithm>
#include<iostream>
#define ll long long
#define ull unsigned long long
using namespace std;
const int N=1e9+7;
const int M=35;
char a[M][M][M]; // 存放地图
int b[M][M][M];  //标记数组
int c[6][3]= {{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}}; //方向数组
int l,m,n,i,j,k,sx,sy,sz;

struct node
{
int x;
int y;
int z;
int step;
} ;

queue<node>q;

bool check(int xx,int yy,int zz)
{
return xx>=0&&yy>=0&&zz>=0&&xx<l&&yy<m&&zz<n&&a[xx][yy][zz]!='#'&&b[xx][yy][zz]!=1; //判断是否合法
}

int bfs()
{
while(!q.empty()) q.pop();
node d,e,f;
d.x=sx,d.y=sy,d.z=sz,d.step=0;
b[sx][sy][sz]==1;
q.push(d);
while(!q.empty())
{
e=q.front();
if(a[e.x][e.y][e.z]=='E') return e.step;
q.pop();
for(i=0; i<6; i++)
{
f.x=e.x+c[i][0];
f.y=e.y+c[i][1];
f.z=e.z+c[i][2];
if(check(f.x,f.y,f.z))
{
b[f.x][f.y][f.z]=1;
f.step=e.step+1;
q.push(f);
}
}
}
return 0;
}

int main()
{
while(~scanf("%d%d%d",&l,&m,&n))
{
if(l==0&&m==0&&n==0) break;
memset(b,0,sizeof(b));
for(i=0; i<l; i++)
{
for(j=0; j<m; j++)
{
scanf("%s",a[i][j]);
for(k=0; k<n; k++)
{
if(a[i][j][k]=='S')
{
sx=i,sy=j,sz=k;  //起点位置
}
}
}
}
int ans=0;
ans=bfs();
if(ans) printf("Escaped in %d minute(s).\n",ans);
else printf("Trapped!\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  广搜