首页 > 学院 > 开发设计 > 正文

Dungeon Master [bfs]

2019-11-11 05:03:26
字体:
来源:转载
供稿:网友

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!

Sample Input

3 4 5S.....###..##..###.#############.####...###########.#######E1 3 3S###E####0 0 0

Sample Output

Escaped in 11 minute(s).Trapped!

解题报告

只要细心就是水题,bfs走一遍即可

#include<stdio.h>#include<string.h>#include<queue>#define MAX_N 32using namespace std;typedef pair<int,int> P;bool map[MAX_N][MAX_N][MAX_N];int best[MAX_N][MAX_N][MAX_N];int s_x,s_y,s_t,e_x,e_y,e_t,H,W,T;int ox[]={0,0,0,1,-1};int oy[]={0,1,-1,0,0};int ot[]={0,1,-1};void bfs(){ memset(best,0x3f,sizeof(best)); queue<P> que; que.push(make_pair(s_x+s_y*H,s_t)); best[s_t][s_x][s_y]=0; while(!que.empty()){ int X=que.front().first%H,Y=que.front().first/H,now=que.front().second;que.pop(); int step=best[now][X][Y]; if(X==e_x&&Y==e_y&&now==e_t){ printf("Escaped in %d minute(s)./n",step); return ; } for(int i=0;i<5;i++){ int x=ox[i]+X; int y=oy[i]+Y; if(0<=x&&x<H&&0<=y&&y<W&&map[now][x][y]){ for(int u=0;u<3;u++){ int el=ot[u]+now; int r=ot[u]&&i>0?1:0; if(T>el&&el>=0&&map[el][x][y]&&best[el][x][y]>step+1+r){ best[el][x][y]=step+1+r; que.push(make_pair(x+y*H,el)); } } } } } puts("Trapped!");}int main(){ char str[32]; while(~scanf("%d%d%d",&T,&H,&W)&&T&&H&&W){ for(int t=0;t<T;t++) for(int i=0;i<H;i++){ scanf("%s",str); for(int j=0;j<W;j++){ switch(str[j]){ case 'S':s_x=i,s_y=j,s_t=t;map[t][i][j]=true;break; case 'E':e_x=i,e_y=j,e_t=t;map[t][i][j]=true;break; case '.':map[t][i][j]=true;break; case '#':map[t][i][j]=false;break; } } } bfs(); } return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表