/*
就是二维变成了三维,模版题。
*/
#include <iostream>
#include <cstring>
#include <string>
#include <queue>
using namespace std;
int k,a,b,c,t;
int mp[55][55][55];
bool vis[55][55][55];
const int dp[6][3]={ {1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1} };
struct Point {
int x,y,z,step;
};
void DataIn() {
scanf("%d%d%d%d", &a,&b,&c,&t);
for (int i=0; i<a; i++) {
for (int j=0; j<b; j++) {
for (int h=0; h<c; h++) {
scanf("%d", &mp[i][j][h]);
}
}
}
}
bool Check(Point &p) {
if (p.x<0 || p.x>=a || p.y<0 || p.y>=b || p.z<0 || p.z>=c || vis[p.x][p.y][p.z] || mp[p.x][p.y][p.z]) return false;
return true;
}
void Bfs() {
memset(vis,false,sizeof(vis));
queue<Point> qu;
Point now,next;
now.x=now.y=now.z=now.step=0;
qu.push(now);
vis[now.x][now.y][now.z]=true;
while (!qu.empty()) {
now=qu.front();
qu.pop();
if (now.x==a-1 && now.y==b-1 && now.z==c-1 && now.step<=t) {
printf("%d
", now.step);
return ;
}
for (int i=0; i<6; i++) {
next=now;
next.x+=dp[i][0];
next.y+=dp[i][1];
next.z+=dp[i][2];
if (!Check(next)) continue;
vis[next.x][next.y][next.z]=true;
next.step=now.step+1;
qu.push(next);
}
}
printf("-1
");
return ;
}
int main() {
scanf("%d", &k);
while (k--) {
DataIn();
Bfs();
}
return 0;
}