#include <iostream> using namespace std; int mx[4]={1,-1,0,0}; int my[4]={0,0,1,-1}; int map[10][10]; int map1[10][10]; int n; int high; int wide; int xx1,yy1,xx2,yy2; int blmin; void slip(int nx1,int ny1,int nx2,int ny2,int step); void search(); bool stop(int x,int y); int main() { freopen("in.txt","r",stdin); cin >>n; for(int i=0;i<n;i++) { blmin=10; cin >>high; cin >>wide; for(int j=0;j<high;j++) { for(int k=0;k<wide;k++) { cin >>map[j][k]; map1[j][k]=map[j][k]; } } search(); slip(xx1,yy1,xx2,yy2,0); if(blmin==10) blmin=-1; cout <<blmin<<endl; /*for(int i=0;i<high;i++) { for(int j=0;j<wide;j++) { cout <<map1[i][j]<<" "; } cout <<endl; } cout <<xx1<<endl; cout <<yy1<<endl; cout <<xx2<<endl; cout <<yy2<<endl; cout <<step<<endl;*/ } return 0; } void search() { for(int i=0;i<high;i++) for(int j=0;j<wide;j++) { if(map[i][j]==1) { xx1=i; yy1=j; } if(map[i][j]==2) { xx2=i; yy2=j; } } } bool stop(int x,int y) { bool ret=true; if(x>=high||y>=wide||x<0||y<0||map[x][y]==9||map1[x][y]==1||map1[x][y]==2) ret=false; return ret; } void slip(int nx1,int ny1,int nx2,int ny2,int step) { int ret; if(step==9) return; if(map[nx1][ny1]==-1&&map[nx2][ny2]==-2) { if(step<blmin) blmin=step; return; } for(int i=0;i<4;i++) { int a=nx1; int b=ny1; int c=nx2; int d=ny2; map1[nx1][ny1]=0; while(1) { a=a+mx[i]; b=b+my[i]; ret=stop(a,b); if(ret==false) { a=a-mx[i]; b=b-my[i]; break; } } map1[a][b]=1; map1[nx2][ny2]=0; while(1) { c=c+mx[i]; d=d+my[i]; ret=stop(c,d); if(ret==false) { c=c-mx[i]; d=d-my[i]; break; } } map1[c][d]=2; map1[a][b]=0; while(1) { a=a+mx[i]; b=b+my[i]; ret=stop(a,b); if(ret==false) { a=a-mx[i]; b=b-my[i]; break; } } map1[a][b]=1; slip(a,b,c,d,step+1); map1[a][b]=0; map1[c][d]=0; map1[nx1][ny1]=1; map1[nx2][ny2]=2; } }