#include<string.h>
#include<stdio.h>
int a,b,c,pos[52][52][52];
struct POS
{
int x,y,z;
} q[125110];
int bfs()
{
int s,e,i;
struct POS temp,t;
int jx[] = {0,0,0,0,1,-1};
int jy[] = {0,0,-1,1,0,0};
int jz[] = {-1,1,0,0,0,0};
s = e = 0;
q[e].x = q[e].y = q[e].z = 0;
e++;
while(s < e)
{
temp = q[s];
s++;
if(temp.x == a-1 && temp.y == b-1 && temp.z == c-1) return (1);
for(i = 0; i < 6; i++)
{
t.x = temp.x + jx[i];
t.y = temp.y + jy[i];
t.z = temp.z + jz[i];
if(t.x >= 0 && t.x < a && t.y >= 0 && t.y < b && t.z >= 0 && t.z < c && pos[t.x][t.y][t.z] == 0 )
{
q[e] = t;
e++;
pos[t.x][t.y][t.z] = pos[temp.x][temp.y][temp.z] + 1;
}
}
}
return 0;
}
int main()
{
memset(pos,-1,sizeof(pos));
int i,j,k,js,t;
scanf("%d",&js);
while(js--)
{
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",&pos[i][j][k]);
if(pos[i][j][k] == 1) pos[i][j][k] = -1;
}
pos[0][0][0] = 0;//起点是 1 也能走
if(!bfs()) printf("-1\n");
else if(pos[a-1][b-1][c-1] <= t) printf("%d\n",pos[a-1][b-1][c-1]);
else printf("-1\n");
}
return 0;
}