#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#define maxn 55
using namespace std;
struct node
{
int x, y,z;
int time;
};
int map[maxn][maxn][maxn];
int a,b,c,t;
int movex[6] = { 1, -1, 0, 0, 0, 0};
int movey[6] = { 0, 0, 1, -1, 0 ,0};
int movez[6] = { 0, 0 ,0 , 0, 1, -1};
bool check( int x, int y, int z)
{
if( x >= 0 && x <a && y >= 0 && y<b && z >= 0 && z < c)
return true;
return false;
}
int bfs()
{
queue<node> que;
node now,temp;
now.x = 0;
now.y = 0;
now.z = 0;
now.time = 0;
que.push(now);
map[now.x][now.y][now.z] = 1;
while(!que.empty())
{
temp = que.front();
que.pop();
for( int i =0; i<6; i++)
{
now.x = temp.x + movex[i];
now.y = temp.y + movey[i];
now.z = temp.z + movez[i];
now.time = temp.time+1;
if( now.x == a -1 && now.y == b-1 && now.z == c -1)
return now.time;
if( check(now.x, now.y, now.z) && map[now.x][now.y][now.z] != 1)
{
que.push(now);
map[now.x][now.y][now.z] = 1;
}
}
}
return -1;
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
scanf("%d%d%d%d",&a, &b, &c, &t);
//getchar();
for( int i = 0; i < a; i++)
{
for( int j = 0; j < b; j++)
{
for( int k =0; k < c; k++)
scanf("%d",&map[i][j][k]);
// getchar();
}
// getchar();
}
if(a+b+c -3 > t || map[a-1][b-1][c-1] == 1)
{
printf("-1\n");
continue;
}
else
printf("%d\n",bfs());
}
return 0;
}