题目大意:在一个三维迷宫中,问你从起点到终点的最小步数。
分析:和HDU1253差不多,简单的三维BFS。
实现代码:
#include <cstdio> #include <iostream> #include <cstring> using namespace std; int dir[6][3]={{1,0,0},{0,1,0},{0,0,1},{-1,0,0},{0,-1,0},{0,0,-1}}; int map[55][55][55]; bool s[55][55][55]; int a,b,c; int cx,cy,cz; int sx,sy,sz,ex,ey,ez; typedef struct node { int x,y,z,tmp; }point; point que[51*51*51]; bool go(int x,int y,int z) { if(x<=0||x>a||y<=0||y>b||z<=0||z>c) return false; else return true; } void bfs(int sx,int sy,int sz) { int x,y,z; int cmp1=1,cmp2=1; que[cmp1].x=sx; que[cmp1].y=sy; que[cmp1].z=sz; que[cmp1].tmp=0; s[sx][sy][sz]=true; while(cmp1<=cmp2&&!s[ex][ey][ez]) { x=que[cmp1].x; y=que[cmp1].y; z=que[cmp1].z; for(int i=0;i<6;i++) if(map[x+dir[i][0]][y+dir[i][1]][z+dir[i][2]]) { cx=x+dir[i][0]; cy=y+dir[i][1]; cz=z+dir[i][2]; if(go(cx,cy,cz)&&!s[cx][cy][cz]) { cmp2++; que[cmp2].x=cx; que[cmp2].y=cy; que[cmp2].z=cz; que[cmp2].tmp=que[cmp1].tmp+1; s[cx][cy][cz]=true; } } cmp1++; } if(cmp1>cmp2) puts("Trapped!"); else printf("Escaped in %d minute(s).\n",que[cmp2].tmp); } int main() { int cas,i,j,k; char tmp; while(scanf("%d%d%d",&a,&b,&c)) { if(a==0&&b==0&&c==0) break; memset(map,1,sizeof(map)); for(i=1;i<=a;i++) for(j=1;j<=b;j++) for(k=1;k<=c;k++) { cin>>tmp; if(tmp=='#') map[i][j][k]=0; if(tmp=='S'){sx=i;sy=j;sz=k;} if(tmp=='E'){ex=i;ey=j;ez=k;} } memset(s,false,sizeof(s)); bfs(sx,sy,sz); } return 0; }