1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public: int minKnightMoves(int x, int y) { x = abs(x), y = abs(y); unordered_map<int, int> m{{0, 0}}; int dx[] = {1, 2, 2, 1, -1, -2, -2, -1}, dy[] = {2, 1, -1, -2, -2, -1, 1, 2}; using tdii = tuple<double, int, int>; priority_queue<tdii, vector<tdii>, greater<tdii>> q; q.emplace(0, 0, 0); while (!q.empty()) { auto [_, xx, yy] = q.top(); q.pop(); if (xx == x && yy == y) return m[x * 1000 + y]; for (int i = 0; i < 8; ++i) { int nx = xx + dx[i], ny = yy + dy[i], k = nx * 1000 + ny; if (nx < -1 || ny < -1 || abs(nx) + abs(ny) > 300 || m.count(k)) continue; m[k] = m[xx * 1000 + yy] + 1; q.emplace(m[k] + dist(nx, ny, x, y), nx, ny); } } return 0; }
double dist(int xx, int yy, int x, int y) { return sqrt((xx - x) * (xx - x) + (yy - y) * (yy - y)); } };
|