NYOJ 523
View Code
1 /* 2 简单的 BFS 相当于三维迷宫 3 4 */ 5 #include<iostream> 6 #include<cstdio> 7 #include<cstring> 8 #include<queue> 9 using namespace std; 10 11 const int size = 55; 12 13 int map[size][size][size]; 14 struct node 15 { 16 int x,y,z; 17 int step; 18 }sta[size*size*size]; 19 int st=0; 20 queue <node> q; 21 22 int bfs(int A,int B,int C) 23 { 24 while(!q.empty())q.pop(); 25 int i,j,k,total=10000; 26 node no; 27 no.x=0; 28 no.y=0; 29 no.z=0; 30 no.step=0; 31 q.push(no); 32 map[0][0][0]=1; 33 while(!q.empty()) 34 { 35 node p = q.front(); 36 q.pop(); 37 i=p.x; 38 j=p.y; 39 k=p.z; 40 //printf("\ni=%d,j=%d,k=%d\n\n",i,j,k); 41 if(A-1==i&&B-1==j&&C-1==k)//使用一个方向数组用个循环统一处理减少代码量 42 { 43 total=p.step; 44 break; 45 } 46 if(i>0&&!map[i-1][j][k]) 47 { 48 sta[st].x=i-1; 49 sta[st].y=j; 50 sta[st].z=k; 51 sta[st].step=p.step+1; 52 q.push(sta[st]); 53 st++; 54 map[i-1][j][k]=1; 55 } 56 if(i<A-1&&!map[i+1][j][k]) 57 { 58 sta[st].x=i+1; 59 sta[st].y=j; 60 sta[st].z=k; 61 sta[st].step=p.step+1; 62 q.push(sta[st]); 63 st++; 64 map[i+1][j][k]=1; 65 } 66 if(j>0&&!map[i][j-1][k]) 67 { 68 sta[st].x=i; 69 sta[st].y=j-1; 70 sta[st].z=k; 71 sta[st].step=p.step+1; 72 q.push(sta[st]); 73 st++; 74 map[i][j-1][k]=1; 75 } 76 if(j<B-1&&!map[i][j+1][k]) 77 { 78 sta[st].x=i; 79 sta[st].y=j+1; 80 sta[st].z=k; 81 sta[st].step=p.step+1; 82 q.push(sta[st]); 83 st++; 84 map[i][j+1][k]=1; 85 } 86 if(k>0&&!map[i][j][k-1]) 87 { 88 sta[st].x=i; 89 sta[st].y=j; 90 sta[st].z=k-1; 91 sta[st].step=p.step+1; 92 q.push(sta[st]); 93 st++; 94 map[i][j][k-1]=1; 95 } 96 if(k<C-1&&!map[i][j][k+1]) 97 { 98 sta[st].x=i; 99 sta[st].y=j; 100 sta[st].z=k+1; 101 sta[st].step=p.step+1; 102 q.push(sta[st]); 103 st++; 104 map[i][j][k+1]=1; 105 } 106 } 107 return total; 108 } 109 110 int main() 111 { 112 int i,j,k; 113 int T,A,B,C,iscase; 114 scanf("%d",&iscase); 115 while(iscase--) 116 { 117 scanf("%d%d%d%d",&A,&B,&C,&T); 118 for(i=0;i<A;++i) 119 for(j=0;j<B;++j) 120 for(k=0;k<C;++k) 121 scanf("%d",&map[i][j][k]); 122 int temp = bfs(A,B,C); 123 //printf("temp=%d\n",temp); 124 if(temp<=T)printf("%d\n",temp); 125 else printf("-1\n"); 126 } 127 return 0; 128 }