#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int map[10][10], ac[4][2] = {0, 1, 0, -1, -1, 0, 1, 0};
struct Maze
{
int x, y, step, eng;
} r, s, t;
int n, m;
int Bfs(int a, int b)
{
r.x = a; r.y = b; r.step = 0; r.eng = 6;
queue<Maze> Q;
Q.push(r);
while(!Q.empty())
{
s = Q.front(); Q.pop();
for(int i = 0; i < 4; i++)
{
t.x = s.x + ac[i][0];
t.y = s.y + ac[i][1];
t.step = s.step + 1;
t.eng = s.eng - 1;
if(t.x >= 0 && t.x < n && t.y >= 0 && t.y < m && map[t.x][t.y] != 0 && t.eng > 0)
{
if(map[t.x][t.y] == 3)
return t.step;
if(map[t.x][t.y] == 4)
{
map[t.x][t.y] = 1; /***********************/
t.eng = 6;
}
Q.push(t);
}
}
}
return -1;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int x, y, i, j;
scanf("%d %d", &n, &m);
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
{
scanf("%d", &map[i][j]);
if(map[i][j] == 2)
{
x = i;
y = j;
}
}
printf("%d\n", Bfs(x, y));
}
return 0;
}