1. 程式人生 > >POJ - 2251 Dungeon Master (三維bfs)

POJ - 2251 Dungeon Master (三維bfs)

/*
三維bfs
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn=30+5;
int L,R,C;
char mp[maxn][maxn][maxn];
bool vis[maxn][maxn][maxn];
int sx,sy,sz,ex,ey,ez;//起點、終點
int dis[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0
,0}}; //6個方向(東南西北上下) struct node { int x,y,z; int step; }; bool check(int x,int y,int z) { if(x<0||y<0||z<0||x>=L||y>=R||z>=C) return 0; else if(mp[x][y][z]=='#') return 0; else if(vis[x][y][z]) return 0; return 1; } int bfs() { node work,next; queue
<node>
qu; work.x=sx; work.y=sy; work.z=sz; work.step=0; vis[sx][sy][sz]=1;//標記已走過的 qu.push(work); while(!qu.empty()) { work=qu.front(); qu.pop(); if(work.x==ex&&work.y==ey&&work.z==ez) return work.step; for
(int i=0;i<6;i++)//列舉6個方向 { next.x=work.x+dis[i][0]; next.y=work.y+dis[i][1]; next.z=work.z+dis[i][2]; if(check(next.x,next.y,next.z))//下一步合法 { vis[next.x][next.y][next.z]=1; next.step=work.step+1; qu.push(next); } } } return 0; } int main() { while(~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=i; sy=j; sz=k; } if(mp[i][j][k]=='E') { ex=i; ey=j; ez=k; } } } } memset(vis,0,sizeof(vis)); int ans=bfs(); //printf("%d\n",ans); if(ans) { printf("Escaped in %d minute(s).\n",ans); } else { printf("Trapped!\n"); } } return 0; }