题意:给出一三维空间的地牢,要求求出由字符'S'到字符'E'的最短路径移动方向可以是上,下,左,右,前,后,六个方向,每移动一次就耗费一分钟,要求输出最快的走出时间。不同L层的地图,相同RC坐标处是连通的,“#”不可通过,“.”可走。
分析:最短路Bfs,和二维的基本一样,就是原来4个方向,现在6个方向,原来数组是二维,现在是三维,也相当于模板题了。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 #include<algorithm> 6 using namespace std; 7 8 char map[35][35][35]; 9 int vis[35][35][35]; 10 int k,n,m,sx,sy,sz,ex,ey,ez; 11 int dx[6]={-1,1,0,0,0,0}; 12 int dy[6]={0,0,-1,1,0,0}; 13 int dz[6]={0,0,0,0,1,-1}; 14 struct node 15 { 16 int x,y,z,step; 17 }; 18 19 int check(int x,int y,int z) 20 { 21 if(x<0||y<0||z<0||x>=k||y>=n||z>=m||map[x][y][z]=='#'||vis[x][y][z]) 22 return 1; 23 return 0; 24 } 25 26 int bfs() 27 { 28 node a,next; 29 queue<node> Q; 30 a.x=sx; 31 a.y=sy; 32 a.z=sz; 33 a.step=0; 34 vis[sx][sy][sz]=1; 35 Q.push(a); 36 while(!Q.empty()) 37 { 38 a=Q.front(); 39 Q.pop(); 40 if(a.x==ex&&a.y==ey&&a.z==ez) 41 return a.step; 42 for(int i=0;i<6;++i) 43 { 44 next=a; 45 next.x=a.x+dx[i]; 46 next.y=a.y+dy[i]; 47 next.z = a.z+dz[i]; 48 if(check(next.x,next.y,next.z)) 49 continue; 50 vis[next.x][next.y][next.z]=1; 51 next.step=a.step+1; 52 Q.push(next); 53 } 54 } 55 return 0; 56 } 57 58 int main() 59 { 60 while(scanf("%d%d%d",&k,&n,&m),n+m+k) 61 { 62 for(int i=0;i<k;++i) 63 { 64 for(int j=0;j<n;++j) 65 { 66 scanf("%s",map[i][j]); 67 for(int r=0;r<m;++r) 68 { 69 if(map[i][j][r]=='S') 70 { 71 sx=i; 72 sy=j; 73 sz=r; 74 } 75 else if(map[i][j][r]=='E') 76 { 77 ex=i; 78 ey=j; 79 ez=r; 80 } 81 } 82 } 83 } 84 memset(vis,0,sizeof(vis)); 85 int ans; 86 ans=bfs(); 87 if(ans) 88 printf("Escaped in %d minute(s). ",ans); 89 else 90 printf("Trapped! "); 91 } 92 return 0; 93 }