C++ 代码
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
struct point {
int x;
int y;
int level;
point(int _x, int _y, int l) : x(_x), y(_y), level(l) {}
};
int bfs(int x0, int y0, int x1, int y1, int n)
{
int dx[] = { -2,-2,-1,-1,1,1,2,2 }, dy[] = { -1,1,-2,2,-2,2,-1,1 };
if (x0 == x1 && y0 == y1) return 0;
bool vis[300][300];
memset(vis, 0, sizeof(vis));
queue<point> Q;
int a, b, step = 0;
Q.push(point(x0, y0, 0));
while (!Q.empty()) {
point top = Q.front();
if (top.x == x1 && top.y == y1) return top.level;
Q.pop();
for (int i = 0; i < 8; i++) {
a = top.x + dx[i], b = top.y + dy[i];
if (a >= 0 && a < n && b >= 0 && b < n && !vis[a][b]) {
vis[a][b] = 1;
Q.push(point(a, b, top.level+1));
}
}
}
}
int main()
{
int T, n, x0, y0, x1, y1;
int map[300][300];
memset(map, 0, sizeof(map));
cin >> T;
while (T--) {
cin >> n;
cin >> x0 >> y0;
cin >> x1 >> y1;
cout << bfs(x0, y0, x1, y1, n) << endl;
}
return 0;
}