1248:Dungeon Master
时间限制: 1000 ms 内存限制: 65536 KB
提交数: 8637 通过数: 3432
【题目描述】
这题是一个三维的迷宫题目,其中用‘.’表示空地,‘#’表示障碍物,‘S’表示起点,‘E’表示终点,求从起点到终点的最小移动次数,解法和二维的类似,只是在行动时除了东南西北移动外还多了上下。可以上下左右前后移动,每次都只能移到相邻的空位,每次需要花费一分钟,求从起点到终点最少要多久。
【输入】
多组测试数据。
一组测试测试数据表示一个三维迷宫:
前三个数,分别表示层数、一个面的长和宽,后面是每层的平面图。前三个数据为三个零表示结束。
【输出】
最小移动次数。
【输入样例】
3 4 5
S....
.###.
.##..
###.#
#####
#####
##.##
##...
#####
#####
#.###
####E
1 3 3
S##
#E#
###
0 0 0
【输出样例】
Escaped in 11 minute(s).
Trapped!
【提示】
对于题目给出数据的含义就是输入l,r,c,分别代表迷宫有l层,每层长宽分别是c,r。对于数据以可以这样移动:
(1,1,1)->(1,1,2)->(1,1,3)->(1,1,4)->(1,1,5)->(1,2,5)->
(1,3,5)->(1,3,4)->(1,4,4)->(2,4,4)->(2,4,5)->(3,4,,5)
共11步就可以到达终点 对于数据二明显不能到达,则输出Trapped!
这题用BFS解,每次去队首元素,如果是终点则输出结果移动的次数,否则,从该点开始分别向东南西北上下移动(如果可以走的话)并继续搜,如果到队列为空还没搜到解法,则说明无解。
【分析】
这题是一个三维的迷宫题目,很显然,地图和访问数组都是三维的。方向数组六个方向,除了东南西北,还有上和下。
【参考代码】
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N=110;
struct node
{
int z;
int x;
int y;
int step;
};
int l,n,m;
int vis[N][N][N]; //访问数组
char map[N][N][N]; //地图数组
int u[][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}}; //方向数组
void bfs(node s,node e)
{
queue <node> q;
bool flag=true;
q.push(s);
while(!q.empty())
{
node a=q.front();
for(int i=0;i<6;i++)
{
node nw;
nw.z =a.z+u[i][0];
nw.x =a.x+u[i][1];
nw.y =a.y+u[i][2];
nw.step =a.step +1;
if(nw.z >=0 && nw.z <l && nw.x >=0 && nw.x <n && nw.y >=0 && nw.y <m && (!vis[nw.z][nw.x][nw.y]) && map[nw.z][nw.x][nw.y]=='.')
{
q.push(nw);
vis[nw.z][nw.x][nw.y]=1;
if(nw.z==e.z && nw.x==e.x && nw.y==e.y)
{
printf("Escaped in %d minute(s).\n",a.step+1);
flag=false;
return;
}
}
}
q.pop();
}
if(flag)
printf("Trapped!\n");
}
int main()
{
while(scanf("%d%d%d",&l,&n,&m)==3,l+n+m)
{
node s,e;
memset(vis,0,sizeof(vis));
for(int k=0;k<l;k++)
for(int i=0;i<n;i++)
scanf("%s",map[k][i]);
for(int k=0;k<l;k++)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(map[k][i][j]=='S')
{
s.z=k;
s.x=i;
s.y=j;
s.step=0;
}
if(map[k][i][j]=='E')
{
e.z=k;
e.x=i;
e.y=j;
map[k][i][j]='.';
}
}
}
}
bfs(s,e);
}
return 0;
}