您的位置:首页 > 其它

POJ ~ 2251 ~ Dungeon Master (3维BFS)

2017-12-17 20:13 295 查看
题意:给你一个三维的迷宫,可走六个方向(前后左右和上下),问你能否从S走到E。如果能走到按格式输出一个最小时间,走不到输出“Trapped!”。

思路:BFS。多加一维状态就好了。我没开标记数组,而是直接将地图修改了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 100
struct node
{
int x, y, z, step;
}s,e,NOW,NEXT;
int h, m, n;//高,长和宽
int dir[6][3] = { {1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1} };  //6个方向可以走
char MAP[maxn][maxn][maxn];  //地图
bool OK(int z, int x, int y)//判断这点是否可以走
{
if(z >= 0 && z < h && x >= 0 && x < m && y >= 0 && y < n && MAP[z][x][y] != '#')
return true;
return false;
}
int BFS()
{
queue<node> Q;
Q.push(s);
while(Q.size())
{
NOW = Q.front();Q.pop();
if(NOW.x == e.x && NOW.y == e.y && NOW.z == e.z)  return NOW.step;
for(int i = 0; i < 6; i++)
{
NEXT.x = NOW.x + dir[i][0];  NEXT.y = NOW.y + dir[i][1];
NEXT.z = NOW.z + dir[i][2];  NEXT.step = NOW.step + 1;
if(OK(NEXT.z, NEXT.x, NEXT.y) == 1)
{
MAP[NEXT.z][NEXT.x][NEXT.y] = '#';
Q.push(NEXT);
}
}
}
return -1;
}
int main()
{
while(scanf("%d%d%d", &h, &m, &n), h+m+n)
{
for(int i = 0; i < h; i++)
{
for(int j = 0; j < m; j++)
{
for(int k = 0; k < n; k++)
{
//scanf("%c ",&MAP[i][j][k]);
cin>>MAP[i][j][k];
if(MAP[i][j][k] == 'S')
{
s.z = i;
s.x = j;
s.y = k;
s.step = 0;
}
if(MAP[i][j][k] == 'E')
{
e.z = i;
e.x = j;
e.y = k;
}
}
}
}
int ans = BFS();
if(ans != -1)
printf("Escaped in %d minute(s).\n", ans);
else
printf("Trapped!\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: