#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cstdlib>
using namespace std;
int t,m,n,mst,net[25][25],x[4]={1,-1,0,0},y[4]={0,0,1,-1};
bool inq[25][25][25];
struct node{
int x,y,ns,ans;
};
int solve()
{
int xx,yy,zz;
queue<node>q;
q.push({1,1,0,0});
inq[1][1][0]=1;
while(!q.empty())
{
node p=q.front();q.pop();
if(p.x==m&&p.y==n) return p.ans;
for(int i=0;i<4;i++)
{
xx=p.x+x[i];yy=p.y+y[i];zz=net[xx][yy]?p.ns+1:0;
if(xx>=1&&xx<=m&&yy>=1&&yy<=n&&!inq[xx][yy][zz])
if(!net[xx][yy]||p.ns<mst)
{
inq[xx][yy][zz]=1;
q.push({xx,yy,zz,p.ans+1});
}
}
}
return -1;
}
int main()
{
cin>>t;
while(t--)
{
cin>>m>>n>>mst;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
cin>>net[i][j];
cout<<solve()<<endl;
memset(inq,0,sizeof(inq));
}
return 0;
}