1257:Knight Moves

Knight Moves

思路和 最少步数 一致。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<queue>
 5 using namespace std;
 6 
 7 const int N=305;
 8 int n,b[N][N],t[]={2,1,-1,-2,-2,-1,1,2,-1,-2,-2,-1,1,2,2,1};
 9 queue<int> q;
10 
11 void bfs(){
12     while(!q.empty()){
13         int x=q.front();
14         q.pop();
15         int y=q.front();
16         q.pop();
17         for(int i=0;i<8;i++){
18             int nx=x+t[i],ny=y+t[i+8];
19             if(nx>=0&&nx<n&&ny>=0&&ny<n&&(!b[nx][ny]||b[nx][ny]>b[x][y]+1)){
20                 q.push(nx),q.push(ny);
21                 b[nx][ny]=b[x][y]+1;
22             }
23         }
24     }
25 }
26 int main(){
27     int x1,y1,x2,y2,m;
28     cin>>m;
29     while(m--){
30         cin>>n>>x1>>y1>>x2>>y2;
31         memset(b,0,sizeof(b));
32         b[x1][y1]=1;
33         q.push(x1),q.push(y1);
34         bfs();
35         printf("%d\n",b[x2][y2]-1);
36     }
37     return 0;
38 }

 

posted @ 2021-08-13 20:02  Rekord  阅读(234)  评论(2编辑  收藏  举报