#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<string.h>
#include <iostream>
using namespace std;
int map[51][51][51],visited[51][51][51];
int dir[6][3]={{1,0,0},{-1,0,0,},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
int A,B,C,T;
struct coor
{
int x,y,z;
int step;
};
queue<coor>que;
bool judge(int x,int y,int z,int step)
{
if(x<0||y<0||z<0||x>=A||y>=B||z>=C)
return false;
if(map[x][y][z]==1||visited[x][y][z])
return false;
visited[x][y][z]=1;
if(step+A-x+B-y+C-z-3>T)
return false;
return true;
}
bool dfs()
{
int x,y,z,i;
coor in,out;
memset(visited,0,sizeof(visited));
while(!que.empty())
que.pop();
in.x=0;in.y=0;in.z=0;
in.step=0;
que.push(in);
while(!que.empty())
{
out=que.front();
que.pop();
if(out.x==A-1&&out.y==B-1&&out.z==C-1&&out.step<=T)
{
printf("%d\n",out.step);
return true;
}
if(out.step>T)
return false;
for(i=0;i<6;i++)
{
x=out.x+dir[i][0];
y=out.y+dir[i][1];
z=out.z+dir[i][2];
if(!judge(x,y,z,out.step+1))
continue;
in.x=x;in.y=y;in.z=z;
in.step=out.step+1;
que.push(in);
}
}
return false;
}
int main()
{
int i,j,k,cas;
scanf("%d",&cas);
while(cas--)
{
scanf("%d%d%d%d",&A,&B,&C,&T);
for(i=0;i<A;i++)
for(j=0;j<B;j++)
for(k=0;k<C;k++)
scanf("%d",&map[i][j][k]);
if(!dfs())
printf("-1\n");
}
return 0;
}