/*
----------------------------------------------
ACMer: Johnsondu
Time: 19:45 - 20:13 2012.2.13
Stratege: BFS , 多开一个二维数组,进行存储当前
坐标所剩下的时间,好进行对比
Problem : 1072 ( Nightmare ) Judge Status : Accepted
RunId : 5349088 Language : G++ Author : a312745658
-----------------------------------------------
*/
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std ;
#define INF 0xfffffff
int map[10][10] ;
int num[10][10] ; //记录到(x, y)所剩的时间
int r, c, tcase ;
int sx, sy, dx, dy ;
int direct[4][2] = {1, 0, 0, -1, -1, 0, 0, 1} ;
bool flag ;
struct Node
{
int x ;
int y ;
int T ; //剩余时间
int step ; //已走步数或者已用时间
}n, m ;
int main()
{
int i, j ;
cin >> tcase ;
while (tcase --)
{
cin >> r >> c ;
for (i = 1; i <= r; i ++)
for (j = 1; j <= c; j ++)
{
cin >> map[i][j] ;
if (map[i][j] == 2)
sx = i, sy = j ;
if (map[i][j] == 3)
dx = i, dy = j ;
num[i][j] = 0 ; //初始化所剩时间为0
}
flag = false ;
n.x = sx ;
n.y = sy ;
n.T = 6 ;
n.step = 0 ;
num[n.x][n.y] = 6 ; // 起点的时间为6
queue <Node> Q ;
Q.push (n) ;
while (! Q.empty())
{
m = Q.front() ;
Q.pop () ;
if (m.x == dx && m.y == dy && m.T > 0)
{
flag = true ;
break ;
}
if (m.T <= 0)
continue ;
if (map[m.x][m.y] == 4) //碰到Reset Time
{
m.T = 6 ;
num[m.x][m.y] = 6 ;
}
for (i = 0; i < 4; i ++)
{
n.x = m.x + direct[i][0] ;
n.y = m.y + direct[i][1] ;
n.T = m.T - 1 ;
n.step = m.step + 1;
if (n.x > 0 && n.y > 0 && n.x <= r && n.y <= c && map[n.x][n.y] != 0 && n.T > 0)
{
if (n.T <= num[n.x][n.y]) //如果当前所用时间比原来时间断,不入队列
continue ;
num[n.x][n.y] = n.T ;
Q.push (n) ;
}
}
}
if (flag)
printf ("%d\n", m.step) ;
else
printf ("-1\n") ;
}
return 0 ;
}