/*
方法借鉴了hdOj论坛,没有处理过可以往回走的题目,所以处理起来很棘手,
第一次爆内存了,对于输出是-1的情况的,我起初考虑的是有点问题的,但是不知怎么解决
后来看了论坛,想想应该是自己的代码造成死循环的缘故吧。
bfs的变形真的让人有点那个的。。
*/
#include<iostream>//2399633 2010-04-29 19:31:23 Accepted 1072 0MS 292K 1915 B C++ 悔惜晟
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
int si, sj;
int ei, ej;
int num;
int n, m;
char map[10][10];
int hash[10][10];//这个hash 有点帅。。。
int dir[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
struct node
{
int time;
int x;
int y;
//int count;
};
int bfs(int sx, int sy)
{
node N, P;
int i;
queue<node>q;
N.x = sx;
N.y = sy;
N.time = 0;
hash[N.x][N.y] = 6;//完美的处理
//N.count = 6;
q.push(N);
while(!q.empty())
{
N = q.front();
/*
if(N.x == ei && N.y == ej && hash[N.x][N.y] > 0)
{
printf("%d/n", N.time);
return 1;
}
*/
/*
if(N.time >= num)
{
break;
}
*/
q.pop();
for(i = 0; i < 4; i++)
{
P.x = N.x + dir[i][0];
P.y = N.y + dir[i][1];
//P.count = N.count - 1;
P.time = N.time + 1;
if(hash[N.x][N.y] <= 1 || P.x < 0 || P.x >= n || P.y < 0 || P.y >= m || map[P.x][P.y] == '0')
continue;
/*
if(map[P.x][P.y] == '1' || map[P.x][P.y] == '3')
{
q.push(P);
if(hash[P.x][P.y] < hash[N.x][N.y] - 1)
hash[P.x][P.y] = hash[N.x][N.y] - 1;
}
*/
if(map[P.x][P.y] == '3')
{
printf("%d/n", P.time);
return 1;
}
if(hash[P.x][P.y] < hash[N.x][N.y] - 1)
{
hash[P.x][P.y] = hash[N.x][N.y] - 1;
if(map[P.x][P.y] == '4')
{
//P.count = 6;
hash[P.x][P.y] = 6;
//q.push(P);
}
q.push(P);
}
}
}
printf("-1/n");
return 1;
}
int main()
{
int T;
int i, j;
cin>>T;
while(T--)
{
cin>>n>>m;
for(i = 0; i < n; i++)
for(j = 0 ; j <m; j++)
{
cin>>map[i][j];
//hash[i][j] = 6;
if(map[i][j] == '2')
{
si = i;
sj = j;
}
if(map[i][j] == '3')//没有用的
{
ei = i;
ej = j;
}
}
//num =2 * (int)(abs(1.0 * si - ei) +abs(1.0 * sj - ej));
memset(hash, -1, sizeof(hash));
bfs(si, sj);
}
}