POJ 2251 Dungeon Master(三維BFS)
阿新 • • 發佈:2018-12-02
題目看起來很厲害,實際上看懂了並不難,開一個三維的陣列,這裡需要注意的是第一維是高度,然後就是簡單的BFS了,還有不同就是三維的時候有六個方向可以走,在前後左右的基礎上多了一個向上和向下的走法,還有一個問題就是多個輸入樣例要注意每次都要初始化,我做的時候就因為這個WA了好幾次,最後在學姐的幫助下才改出來,最後,附程式碼如下:
#include<iostream> #include<cstdio> #include<cstring> using namespace std; char mp[50][50][50]; int step[50][50][50],vis[50][50][50]; int mv[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}}; int l,r,c,sx,sy,sz,ex,ey,ez; struct node { int z,x,y; }; void bfs() { memset(vis,0,sizeof(vis)); node que[100010]; int frt = 0,til = 0; que[til].x = sx; que[til].y = sy; que[til++].z = sz; step[sz][sx][sy] = 0; vis[sz][sx][sy] = 1; while(frt != til) { node p = que[frt++]; int next_x,next_y,next_z; for(int i = 0;i < 6; i++) { next_x = p.x + mv[i][0]; next_y = p.y + mv[i][1]; next_z = p.z + mv[i][2]; if(next_x >= 0 && next_x < r && next_y >= 0 && next_y < c && next_z >= 0 && next_z < l && mp[next_z][next_x][next_y] != '#' && !vis[next_z][next_x][next_y]) { que[til].x = next_x; que[til].y = next_y; que[til++].z = next_z; step[next_z][next_x][next_y] = step[p.z][p.x][p.y] + 1; vis[next_z][next_x][next_y] = 1; } if(next_x == ex && next_y == ey && next_z == ez) break; } } } int main() { while(1) { scanf("%d %d %d",&l,&r,&c); if(l == 0 && r == 0 && c == 0) break; for(int i = 0;i < l; i++) { for(int j = 0;j < r; j++) { scanf("%s",mp[i][j]); for(int k = 0;k < c; k++) { if(mp[i][j][k] == 'S') { sx = j; sy = k; sz = i; continue; } if(mp[i][j][k] == 'E') { ex = j; ey = k; ez = i; } } } } bfs(); if(step[ez][ex][ey] != 0) printf("Escaped in %d minute(s).\n",step[ez][ex][ey]); else printf("Trapped!\n"); } return 0; }