/*
三维广搜
10072601 | 2014-02-08 14:14:15 | Accepted | 1253 | 1093MS | 1424K | 1337 B | C++ |
*/
#include<iostream>
#include<queue>
#define N 52
using namespace std;
int n, m, h, mark[N][N][N], dir[6][3] = {1,0,0, -1,0,0, 0,1,0, 0,-1,0, 0,0,1, 0,0,-1};
int str[N][N][N];
struct node
{
int x, y, z, step;
};
int judge(int x, int y, int z)
{
if(x>=0 && x<n && y>=0 && y<m && z>=0 &&z<h && mark[x][y][z]==0 && str[x][y][z]==0)
return 1;
else
return 0;
}
int bfs()
{
int i, x, y, z;
node cur, next;
queue<node>q;
cur.x=0; cur.y=0; cur.z=0; cur.step=0;
q.push(cur);
while(!q.empty())
{
cur = q.front();
q.pop();
if(cur.x==n-1 && cur.y==m-1 && cur.z==h-1)
return cur.step;
for( i=0; i < 6; i++ )
{
next.x = x = cur.x + dir[i][0];
next.y = y = cur.y + dir[i][1];
next.z = z = cur.z + dir[i][2];
next.step = cur.step + 1;
if(judge(x, y, z))
{
mark[x][y][z] = 1;
q.push(next);
}
}
}
return -1;
}
int main()
{
int T, times;
scanf("%d", &T);
while(T--)
{
int i, j, k;
scanf("%d%d%d%d", &n, &m, &h, ×);
for( i=0; i < n; i++ )
for( j=0; j < m; j++ )
for( k=0; k < h; k++ )
scanf("%d", &str[i][j][k]);
memset(mark, 0, sizeof(mark));
mark[0][0][0] = 1;
int ans = bfs();
if(ans==-1 || ans > times)
printf("-1\n");
else
printf("%d\n", ans);
}
return 0;
}