ybt1248_Dungeon Master
时空限制 1000ms/64MB
【题目描述】
这题是一个三维的迷宫题目,其中用‘.’表示空地,‘#’表示障碍物,‘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<string>
#include<cstring>
using namespace std;
const int N = 105;
const int dx[] = {-1, 0, 1, 0, 0, 0},
dy[] = { 0, 1, 0,-1, 0, 0},
dz[] = { 0, 0, 0, 0, 1,-1};
//后 右 前 左 上 下
int L,r,c,que[N*N][4];
int x1,y1,z1,x2,y2,z2;
bool g[N][N][N];
void bfs(){
memset(que,0,sizeof(que));
int head=0,tail=1,ans=0;
que[1][1]=x1; que[1][2]=y1; que[1][3]=z1; que[1][0]=0;
g[x1][y1][z1] = false;
bool OK=false;
while (head<tail){
head++;
for (int i=0; i<6; i++){
int xx=que[head][1]+dx[i],yy=que[head][2]+dy[i],zz=que[head][3]+dz[i];
if (xx>=0 && xx<L && yy>=0 && yy<r && zz>=0 && zz<c && g[xx][yy][zz]){
tail++;
que[tail][1]=xx;
que[tail][2]=yy;
que[tail][3]=zz;
que[tail][0]=que[head][0]+1;
g[xx][yy][zz] = false;
if (xx==x2 && yy==y2 && zz==z2){
cout<<"Escaped in "<<que[head][0]+1<<" minute(s)."<<endl;
OK=true; break;
}
}
}
if (OK) break;
}
if (!OK) cout<<"Trapped!"<<endl;
}
int main(){
while (cin>>L>>r>>c){
if (!L && !r && !c) break;
string s;
for (int i=0; i<L; i++)
for (int j=0; j<r; j++){
cin>>s;
for (int k=0; k<c; k++)
if (s[k]=='S') x1=i,y1=j,z1=k;
else if (s[k]=='E') x2=i,y2=j,z2=k,g[i][j][k]=true;
else if (s[k]=='.') g[i][j][k]=true;
else g[i][j][k]=false;
}
bfs();
}
return 0;
}