1 #include <cstdio>
2 #include <queue>
3 using namespace std;
4
5 struct Edge {
6 int a, b, c , time;
7 void init( int x, int y , int z, int cost){
8 a = x;
9 b = y;
10 c = z;
11 time = cost;
12 }
13 };
14
15 queue<Edge > Q;
16 int buf[ 50][50 ][50];
17 bool mark[ 50][50 ][50];
18 int go[ 6][3 ] = { { - 1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 }, { 1 , 0 , 0 }, { 0 , 1 ,
19 0 }, { 0, 0, 1 } };
20
21 int bfs( int a, int b , int c) {
22 Edge tmp ;
23 Edge e ;
24 int x, y, z ;
25 tmp .init( 0, 0, 0, 0);
26 Q .push( tmp);
27 while (! Q.empty ()) {
28 tmp = Q. front();
29 Q .pop();
30 if(tmp .a == a - 1 && tmp.b == b - 1 && tmp. c == c - 1 )
31 return tmp. time;
32 for ( int i = 0; i < 6; i ++) {
33 x = tmp. a + go [i][ 0];
34 y = tmp. b + go [i][ 1];
35 z = tmp. c + go [i][ 2];
36 if ( x < 0 || x >= a || y < 0 || y >= b || z < 0 || z >= c
37 || buf[ x][y ][z] || mark [x][ y][z ])
38 continue;
39 e .init( x, y , z, tmp.time + 1 );
40 mark [x][ y][z ] = true;
41 Q .push( e);
42 }
43 }
44 return - 1;
45 }
46
47 int main() {
48 int K;
49 int A, B, C , T;
50 while (~ scanf("%d" , & K)) {
51 while ( K--) {
52 while(!Q .empty())
53 Q .pop();
54 scanf ("%d%d%d%d", &A , & B, &C, &T );
55 for ( int i = 0; i < A ; i++)
56 for ( int j = 0; j < B ; j++)
57 for ( int k = 0; k < C ; k++)
58 mark [i][ j][k ] = false;
59 for ( int i = 0; i < A ; i++)
60 for ( int j = 0; j < B ; j++)
61 for ( int k = 0; k < C ; k++){
62 scanf ("%d", &buf [i][ j][k ]);
63 }
64 int time = bfs(A , B, C);
65 if(time <= T)
66 printf ("%d\n", time);
67 else
68 printf ("-1\n");
69 }
70 }
71 return 0 ;
72 }
73