Is an escape possible? If yes, how long will it take?
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.
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!
3 4 5 S.... .###. .##.. ###.# ##### ##### ##.## ##... ##### ##### #.### ####E 1 3 3 S## #E# ### 0 0 0
Escaped in 11 minute(s).Trapped!
题意:你被困在3D地下城,需要找到最快的出路!地下城由单位立方体组成,可能填充或不填充岩石。移动一个单位北,南,东,西,上或下需要一分钟。您不能对角移动,迷宫四周都是坚实的岩石。 逃避可能吗?如果是,需要多长时间? 输入 输入由许多地下城组成。每个地下城描述以包含三个整数L,R和C(均大小限制在30)的行开头。 L是构成地牢的等级数。 R和C是构成每个级别的计划的行数和列数。 然后将会有L个R行,每行包含C个字符。每个角色描述地下城的一个单元格。充满岩石的细胞用'#'表示,空单元由'。'表示。你的起始位置用'S'表示,并用字母'E'表示。每个级别后面都有一条空白行。对于L,R和C,输入终止三个零。 输出 每个迷宫产生一行输出。如果可以到达出口,打印一行表格 在x分钟内逃脱。 其中x被逃离所需的最短时间所取代。 如果不能逃脱,打印行 被困! 样例输入 3 4 5 小号.... 。###。 ## .. #### ##### ##### ##。## ## ... ##### ##### #### ####Ë 1 3 3 小号## ·E· ### 0 0 0 样例输出 在11分钟内逃跑。 被困!
思路:三维地图,多了上下两个方向,定义方向数组时要注意,然后用广搜, 找出最短路。 广搜:首先定义一个结构体,再写bfs时,先定义now,next,两个结构体 定义一个队列,判断。
代码:
#include<stdio.h> #include<string.h> #include<queue> using namespace std; int l,r,c; int sx,sy,sz; int ex,ey,ez; char map[35][35][35]; int book[35][35][35]; int dir[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}}; struct node { int x,y,z,step; }; int judge(int x,int y,int z) { if(x<0||x>=l||y<0||y>=r||z<0||z>=c) return 0; else if(map[x][y][z]=='#') return 0; else if(book[x][y][z]) return 0; else return 1; } int bfs() { node now,next; queue<node>q; now.x=sx; now.y=sy; now.z=sz; now.step=0;//初始为0 book[now.x][now.y][now.z]=1;//标记 q.push(now);//初始化队列 while(!q.empty()) { now=q.front(); q.pop(); if(now.x==ex&&now.y==ey&&now.z==ez) { return now.step; } for(int i=0;i<6;i++) { next=now; next.x=now.x+dir[i][0]; next.y=now.y+dir[i][1]; next.z=now.z+dir[i][2]; if(judge(next.x,next.y,next.z)) { next.step=now.step+1; book[next.x][next.y][next.z]=1; q.push(next); } } } return 0; } int main() { while(~scanf("%d%d%d",&l,&r,&c),l+r+c) { for(int i=0;i<l;i++) { for(int j=0;j<r;j++) { scanf("%s",map[i][j]); for(int k=0;k<c;k++) { if(map[i][j][k]=='S') { sx=i; sy=j; sz=k; } if(map[i][j][k]=='E') { ex=i; ey=j; ez=k; } } } } memset(book,0,sizeof(book)); int ans=bfs(); if(ans) printf("Escaped in %d minute(s).\n",ans); else printf("Trapped!\n"); } return 0; }