#include <iostream>
#include <queue>
using namespace std;
struct node
{
int x,y;
int t,time;
};
int a[15][15],visit[15][15];
int n,m,dist[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
int sx,sy,outx,outy;
int bfs()
{
queue<node> path;
node p,q;
p.x=sx,p.y=sy,p.t=0,p.time=6;
path.push(p);
while(!path.empty())
{
p=path.front();
path.pop();
if(p.x == outx && p.y == outy)return p.t;
if(p.time<=1)continue;
for(int i=0; i<4; i++)
{
q.x = p.x+dist[i][0];
q.y = p.y+dist[i][1];
if(q.x<n && q.x>=0 && q.y<m && q.y>=0 && a[q.x][q.y]!=0 && visit[q.x][q.y]!=1)
{
q.t = p.t+1;
q.time = p.time-1;
if(a[q.x][q.y] == 4)
{
q.time=6;
visit[q.x][q.y]=1;
}
path.push(q);
}
}
}
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>m;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin>>a[i][j];
if(a[i][j] == 2)
{
sx=i;
sy=j;
}
else if(a[i][j] == 3)
{
outx=i,outy=j;
}
visit[i][j]=0;
}
}
cout<<bfs()<<endl;
}
return 0;
}