#include
using namespace std;
using ll = long long;
int grid[1009][1009];
int n,a1,a2,b1,b2;
int dir[8][2] = { 2,1,1,2,-1,2,-2,1,-2,-1,-1,-2,1,-2,2,-1 };
struct knight {
int x, y, g, h, f;//f=g+h,g起点到当前结点,h当前结点到终点
};
struct cmp {
bool operator()(const knight& a, const knight& b) {
return a.f > b.f;
}
};
priority_queue<knight,vector<knight>,cmp>q;
int getDist(const int &x,const int &y,const int &b1,const int &b2) {
return (x - b1) * (x - b1) + (y - b2) * (y - b2);
}
void bfs() {
q.push({ a1,a2,0,getDist(0,0,b1,b2),getDist(0,0,b1,b2)});
while (!q.empty()) {
knight cur = q.top();
q.pop();
if (cur.x == b1 && cur.y == b2) {
cout << grid[cur.x][cur.y] << endl;
return;
}
knight next;
for (int k = 0;k<8; k++) {
next.x = cur.x + dir[k][0];
next.y = cur.y + dir[k][1];
if (next.x < 1 || next.x>1000 || next.y < 1 || next.y>1000) {
continue;
}
if (!grid[next.x][next.y]) {
grid[next.x][next.y] = grid[cur.x][cur.y] + 1;//更新距离,并且起到标记作用
next.g = cur.g + 5;
next.h = getDist(next.x, next.y, b1, b2);
next.f = next.g + next.h;
q.push(next);
}
}
}
}
void solve(){
cin >> n;
while (n--) {
cin >> a1 >> a2 >> b1 >> b2;
memset(grid, 0, sizeof(grid));
bfs();
while (!q.empty()) {
q.pop();
}
}
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0); std::cout.tie(0);
solve();
return 0;
}
next.g=getDist(next.x,next.y,a1,a2);计算与源点的距离是错误的蜀黍不会,有缘更新
using namespace std;
using ll = long long;
vector<vector<int>>grid(1009, vector<int>(1009, 0));
int n,a1,a2,b1,b2;
int dir[8][2] = { 2,1,1,2,-1,2,-2,1,-2,-1,-1,-2,1,-2,2,-1 };
struct knight {
int x, y, dist;
};
struct cmp {
bool operator()(const knight&a,const knight&b) {
return a.dist > b.dist;
}
};
priority_queue<knight, vector<knight>, cmp>q;
vector<vector<int>>dist(1009, vector<int>(1009, INT_MAX));
void bfs(vector<vector<int>>dist) {
dist[a1][a2] = 0;
q.push({ a1,a2,dist[a1][a2]});
while (!q.empty()) {
knight cur=q.top();
q.pop();
if (cur.x == b1 && cur.y == b2) {
cout << dist[cur.x][cur.y]<<endl;
return;
}
knight next;
for (int k = 0; k < 8; k++) {
//相当于选点操作
next.x = cur.x + dir[k][0];
next.y = cur.y + dir[k][1];
if (next.x < 1 || next.x>1000 ||next.y < 1 || next.y > 1000) {
continue;
}
//因为题目说了一定能找到,所以可以没有visited数组的标记
//相当于更新
if (cur.dist + 1 < dist[next.x][next.y]) {
//注意每走一步+1;dist数组也要更新
dist[next.x][next.y] = cur.dist + 1;
q.push({ next.x,next.y,dist[next.x][next.y] });
}
}
}
}
void solve(){
cin >> n;
while (n--) {
cin >> a1 >> a2 >> b1 >> b2;
bfs(dist);//传入dist数组作为形参
while (!q.empty()) {
q.pop();
}
}
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0); std::cout.tie(0);
solve();
return 0;
}