C++ 代码
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int,int> PII;
const int N = 310;
int g[N][N],n,T;
int vis[N][N];//定义这个来记录步数
int dx[8]={2,1,-1,-2,-2,-1,1,2};
int dy[8]={1,2,2,1,-1,-2,-2,-1};
void bfs(PII s,PII end){
queue<PII> q;
q.push(s);
int ans;
while(q.size()){
auto t = q.front();
q.pop();
if(t.x==end.x&&t.y==end.y){
return;
}
vis[s.x][s.y] = 0;
for(int i=0;i<8;i++){
int x = t.x+dx[i];
int y = t.y+dy[i];
//cout<<x<<" "<<y<<" "<<endl;
if(x<0||x>n||y<0||y>n){
continue;
}
if(vis[x][y]){
continue;
}
q.push({x,y});
vis[x][y] = vis[t.x][t.y]+1;
}
}
}
int main(){
cin>>T;
while(T--){
cin>>n;
memset(g,0,sizeof g);
memset(vis,0,sizeof vis);
PII start,end;
cin>>start.x>>start.y>>end.x>>end.y;
bfs(start,end);
cout<<vis[end.x][end.y]<<endl;
}
}