代码中加入了相应的注释
由于对于C++代码不是很熟悉 可能有些注释有误
C++ 代码
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> PII; //定义一个坐标类型
//使用bfs进行解答
//8个方向上的偏移量 可以循环遍历 少写代码
const int dx[] = {2, 1, -1, -2, -2, -1, 1, 2};
const int dy[] = {1, 2, 2, 1, -1, -2, -2, -1};
const int N = 310;
int n, sx, sy, fx, fy; //(sx, sy)是起点坐标, (fx,fy)是终点坐标
int vis[N][N]; //循环遍历的图表
void bfs(int x, int y)
{
queue<PII> q;
q.push({x, y});
//当队列不为空时进行操作
while(q.size()){
auto t = q.front(); //弹出第一个坐标 进行判断遍历,并将结果放入vis中
q.pop();
if(t.first == fx && t.second == fy) return;
else{
for(int i = 0; i < 8; i++){
//(a, b)是新的坐标
int a = t.first + dx[i];
int b = t.second + dy[i];
//判断是否越界 以及是否访问过
if(a >= 0 && a < n && b >= 0 && b < n && vis[a][b] == 0){
vis[a][b] = vis[t.first][t.second] + 1;
q.push({a, b});
}
}
}
}
}
int main()
{
int t;
cin >> t;
while(t--){
memset(vis, 0, sizeof vis); //memset(x, y, z) x是需要设置的数组指针, y是需要设置的值, z是x的长度
cin >> n;
cin >> sx >> sy;
cin >> fx >> fy;
bfs(sx, sy);
cout << vis[fx][fy] << endl;
}
return 0;
}