Description
You is trapped in a 3D dungeon and need to find the quickest-on-the-do out! The dungeon is composed of a unit cubes which may or may isn't being 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 are surrounded by solid rock in all sides.
is an escape possible? If Yes, how long would it take?
A three-dimensional maze problem, and two-dimensional no difference, direct BFS is good.
The code is as follows:
#include <iostream>#include<cstdio>#include<cstring>#include<queue>using namespacestd;BOOLmap1[ +][ +][ +];BOOLvis[ +][ +][ +];intl,r,c;intSl,sr,sc,el,er,ec;structstate{intL,r,c; intnum; State () {} state (intXintYintZintN): L (x), R (Y), C (z), num (n) {}};BOOLJudgeintXintYintz) { if(x<=0|| x>l| | y<=0|| y>r| | z<=0|| Z>C)return 0; if(map1[x][y][z]==0) return 0; if(Vis[x][y][z])return 0; VIS[X][Y][Z]=1; return 1;}intBFs () {Queue<state>que; State temp; intTL,TR,TC; Que.push (State (SL,SR,SC,0)); while(!Que.empty ()) {Temp=Que.front (); Que.pop (); if(temp.l==el&&temp.r==er&&temp.c==Ec)returnTemp.num; TL=TEMP.L; TR=TEMP.R; TC=temp.c; if(Judge (tl-1, TR,TC)) Que.push (State (TL-1, tr,tc,temp.num+1)); if(Judge (tl+1, TR,TC)) Que.push (State (TL+1, tr,tc,temp.num+1)); if(Judge (tl,tr-1, TC)) Que.push (State (Tl,tr-1, tc,temp.num+1)); if(Judge (tl,tr+1, TC)) Que.push (State (Tl,tr+1, tc,temp.num+1)); if(Judge (tl,tr,tc-1)) Que.push (state (TL,TR,TC-1, temp.num+1)); if(Judge (tl,tr,tc+1)) Que.push (state (TL,TR,TC+1, temp.num+1)); } return-1;}intMain () {Chars[ -]; intans; Ios::sync_with_stdio (false); while(cin>>l>>r>>C) {memset (Vis,0,sizeof(VIS)); if(! l&&! r&&!C) Break; for(intI=1; i<=l;++i) for(intj=1; j<=r;++j) {cin>>s; for(intk=1; k<=c;++k)Switch(s[k-1]) { Case 'S': Sl=i; Sr=J; Sc=K; MAP1[I][J][K]=1; Break; Case 'E': El=i; Er=J; Ec=K; MAP1[I][J][K]=1; Break; Case '.': Map1[i][j][k]=1; Break; Case '#': Map1[i][j][k]=0; Break; }} ans=BFS (); if(ans!=-1) cout<<"escaped in"<<ans<<"minute (s). \ n"; Elsecout<<"trapped!\n"; } return 0;}
View Code
Simple POJ 2251 Dungeon Master,bfs.