BFS/poj 2251 Dungeon Master
1 #include<cstdio> 2 #include<queue> 3 #include<cstring> 4 using namespace std; 5 6 const int dx[6]={1,0,-1,0,0,0}; 7 const int dy[6]={0,1,0,-1,0,0}; 8 const int dz[6]={0,0,0,0,1,-1}; 9 10 struct point 11 { 12 int x,y,z; 13 int step; 14 }; 15 16 int L,R,C,ex,ey,ez,sx,sy,sz; 17 char a[30][30][30]; 18 bool v[30][30][30]; 19 20 bool pd(int x,int y,int z) 21 { 22 if (x>=0 && x<C && y>=0 && y<R && z>=0 && z<L && a[z][y][x]!='#' && v[x][y][z]==0) return true; 23 return false; 24 } 25 26 int bfs(int sx,int sy,int sz,int ex,int ey,int ez) 27 { 28 memset(v,0,sizeof(v)); 29 queue<point>que; 30 point now; 31 now.x=sx;now.y=sy;now.z=sz; 32 now.step=0; 33 v[sx][sy][sz]=1; 34 que.push(now); 35 point next; 36 while (!que.empty()) 37 { 38 now=que.front(); 39 que.pop(); 40 if (now.x==ex && now.y==ey && now.z==ez) break; 41 for (int i=0;i<6;i++) 42 { 43 next.x=now.x+dx[i]; 44 next.y=now.y+dy[i]; 45 next.z=now.z+dz[i]; 46 if (pd(next.x,next.y,next.z)) 47 { 48 v[next.x][next.y][next.z]=1; 49 next.step=now.step+1; 50 que.push(next); 51 } 52 } 53 54 } 55 return now.step; 56 } 57 58 int main() 59 { 60 scanf("%d%d%d",&L,&R,&C); 61 while (L!=0) 62 { 63 for (int z=0;z<L;z++) 64 { 65 for (int y=0;y<R;y++) 66 { 67 scanf("%s",a[z][y]); 68 for (int x=0;x<C;x++) 69 { 70 if (a[z][y][x]=='S'){sx=x;sy=y;sz=z;} 71 else if (a[z][y][x]=='E'){ex=x;ey=y;ez=z;} 72 } 73 } 74 } 75 int ans=bfs(sx,sy,sz,ex,ey,ez); 76 if (ans==0) printf("Trapped!\n"); 77 else printf("Escaped in %d minute(s).\n",ans); 78 scanf("%d%d%d",&L,&R,&C); 79 } 80 return 0; 81 }