经典的走马步,BFS里的基友,啊不,基础题,我却花了老长时间。今天做这题时遇到了两个奇葩问题,一是数组越界了居然不RE,当初我的队列只开了300+,然后head都飙到460了程序还正常运行;另一个就是我在BFS里没有对x2,y2进行任何修改,它居然姚明进去,郭敬明出来了。最后还是要感谢Samsara帮我找到了问题,把数组开大了。我想,说不定第二个问题就是由第一个引起的,难道是CodeBlocks太智能了,知道我写的是队列,然后自动*#$……
1 #include <stdio.h> 2 #include <string.h> 3 int map[310][310],end,head; 4 int X[] = {-2,-2,-1,-1,1,1,2,2}, 5 Y[] = {-1,1,-2,2,-2,2,-1,1}; 6 int qx[90010],qy[90010]; 7 int x1,x2,y1,y2; 8 void bfs(int a,int b,int n) 9 { 10 int t1,t2,i; 11 head = end = 0; 12 qx[head] = a; 13 qy[head] = b; 14 map[a][b] = 0; 15 while(head <= end) 16 { 17 a = qx[head]; 18 b = qy[head]; 19 if(x2==a && y2==b) return ; 20 for(i = 0; i < 8; i++) 21 { 22 t1 = a+X[i]; 23 t2 = b+Y[i]; 24 if( t1>= 0 && t1 < n && t2 >= 0 25 && t2 < n && map[t1][t2] == -1) 26 { 27 end++; 28 qx[end] = t1; 29 qy[end] = t2; 30 map[t1][t2] = map[a][b]+1; 31 } 32 } 33 head++; 34 } 35 return ; 36 } 37 int main() 38 { 39 int m,n; 40 while(~scanf("%d",&m)) 41 { 42 while(m--) 43 { 44 scanf("%d%d%d%d%d",&n,&x1,&y1,&x2,&y2); 45 memset(map,-1,sizeof(map)); 46 bfs(x1,y1,n); 47 printf("%d\n",map[x2][y2]); 48 } 49 } 50 return 0; 51 }