5 5 5 0 1 0 0 0 0 0 0 0 0 0 2 0 9 0 0 0 0 0 0 0 9 -1 0 -2 4 6 -1 -2 1 0 9 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 4 0 0 0 0 0 0 0 9 2 0 1 0 0 0 9 0 0 9 0 0 0 0 0 0 -1 0 -2 0 4 7 0 0 0 0 0 0 0 0 0 1 9 0 0 0 0 0 0 0 0 0 0 9 2 -1 9 0 0 -2 10 10 0 0 0 0 0 0 0 9 -1 0 0 9 -2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 0 9 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 9 9 9 0 0 0 0 0 9 0 0 0 #include<stdio.h> int map[99][99]; int mov1[4]={1,0,-1,0}; int mov2[4]={0,1,0,-1}; int minbu=99999; int cass; int X; int Y; int xx1; int yy1; int xx2; int yy2; int exx1; int eyy1; int exx2; int eyy2; int fangxiang[99]; void zoulu(int x1,int y1,int x2,int y2,int step) { if(minbu<step) return; if(x1==exx1&&y1==eyy1&&x2==exx2&&y2==eyy2&&step<=8) { if(minbu>step) minbu=step; return; } if(step==8) return; for(int i=0;i<4;i++) { int nx1=x1; int ny1=y1; int nx2=x2; int ny2=y2; int lu1=0; int lu2=0; while(map[nx1][ny1]!=9) { nx1=nx1+mov1[i]; ny1=ny1+mov2[i]; if(nx1<0||nx1>=X||ny1<0||ny1>=Y) { break; } lu1++; } nx1=nx1-mov1[i]; ny1=ny1-mov2[i]; while(map[nx2][ny2]!=9) { nx2=nx2+mov1[i]; ny2=ny2+mov2[i]; if(nx2<0||nx2>=X||ny2<0||ny2>=Y) { break; } lu2++; } nx2=nx2-mov1[i]; ny2=ny2-mov2[i]; if(nx1==nx2&&ny1==ny2) { if(lu1>lu2) { nx1=nx1-mov1[i]; ny1=ny1-mov2[i]; } else { nx2=nx2-mov1[i]; ny2=ny2-mov2[i]; } } zoulu(nx1,ny1,nx2,ny2,step+1); } } int main() { freopen("in.txt","r",stdin); scanf("%d",&cass); while(cass--) { minbu=99999; scanf("%d%d",&X,&Y); for(int i=0;i<X;i++) { for(int j=0;j<Y;j++) { scanf("%d",&map[i][j]); if(map[i][j]==1) { xx1=i; yy1=j; map[i][j]=0; } else if(map[i][j]==2) { xx2=i; yy2=j; map[i][j]=0; } else if(map[i][j]==-1) { exx1=i; eyy1=j; } else if(map[i][j]==-2) { exx2=i; eyy2=j; } } } zoulu(xx1,yy1,xx2,yy2,0); if(minbu==99999) printf("-1 "); else printf("%d ",minbu); } return 0; }