1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 #define size 10 6 #define Max 100000 7 using namespace std; 8 struct point{ 9 int x,y,now,l; 10 }; 11 int dx[]={0,1,-1,0},dy[]={-1,0,0,1}; 12 int map[size][size]; 13 int step[size][size],ti[size][size]; 14 int n,m; 15 point start; 16 int x,y,now,l; 17 bool flag; 18 void bfs() 19 { 20 queue<point> s; 21 s.push(start); 22 int i,j; 23 point next; 24 while(!s.empty()) 25 { 26 point pos=s.front(); 27 s.pop(); 28 if(map[pos.x][pos.y]==3) {flag=1;cout<<pos.l<<endl;break;} 29 if(pos.now>1) 30 { 31 for(i=0;i<4;i++) 32 { 33 x=pos.x+dx[i]; 34 y=pos.y+dy[i]; 35 now=pos.now-1; 36 l=pos.l+1; 37 if((x>=0&&y>=0&&x<n&&y<m&&map[x][y]!=0)) 38 { 39 if(map[x][y]==4) {now=6;map[x][y]=0;} 40 next.x=x,next.y=y,next.now=now,next.l=l; 41 s.push(next); 42 } 43 } 44 } 45 } 46 } 47 int main() 48 { 49 int T,i,j; 50 freopen("in.txt","r",stdin); 51 cin>>T; 52 while(T--) 53 { 54 cin>>n>>m; 55 for(i=0;i<n;i++) 56 for(j=0;j<m;j++) 57 { 58 cin>>map[i][j]; 59 if(map[i][j]==2) {start.x=i,start.y=j;} 60 } 61 for(i=0;i<size;i++) 62 for(j=0;j<size;j++) 63 step[i][j]=Max; 64 flag=0; 65 start.now=6,start.l=0; 66 bfs(); 67 if(!flag) cout<<-1<<endl; 68 } 69 }