双向BFS,
但是超时了不知道为啥,话说双向BFS不是更快吗,有没有大佬帮我看看
#include <iostream>
#include <queue>
#include <unordered_map>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
int res = 0;
bool extend(queue<PII>& h, unordered_map<string, int>& h1, unordered_map<string, int>& h2, int size)
{
int addx[8] = { 1,1,-1,-1,2,2,-2,-2 };
int addy[8] = { 2,-2,2,-2,1,-1,1,-1 };
queue<PII> temp;
while(h.size())
{
auto item = h.front();
h.pop();
int dx = item.first; int dy = item.second;
string t = to_string(dx) + "*" + to_string(dy);
if(h2.count(t)) return true;
for(int i = 0; i < 8; i++)
{
int newx = addx[i] + dx; int newy = addy[i] + dy;
if(newx < 0 || newy < 0) continue;
if(newx > size || newy > size) continue;
string s = to_string(newx) + "*" + to_string(newy);
if(h1.count(s)) continue;
temp.push({newx, newy});
h1[s] = 1;
}
}
res++;
swap(h, temp);
return false;
}
int minKnightMoves(int size, int fx, int fy, int x, int y)
{
res = 0;
if(fx == x && fy == y) return 0;
queue<PII> head, tail;
unordered_map<string, int> hash1, hash2;
head.push({fx, fy}); tail.push({x, y});
while(head.size() && tail.size())
{
bool flag = false;
if(head.size() > tail.size())
flag = extend(tail, hash2, hash1, size);
else
flag = extend(head, hash1, hash2, size);
if(flag) return res;
}
return -1;
}
int main()
{
int T;
cin >> T;
while(T--)
{
int size, fx, fy, sx, sy;
scanf("%d%d%d%d%d", &size, &fx, &fy, &sx, &sy);
int n = minKnightMoves(size, fx, fy, sx, sy);
cout << n << endl;
}
return 0;
}