[LeetCode] Minimum Knight Moves

1197. Minimum Knight Moves

In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].

A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists.

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
27
28
29
class Solution {
public:
int minKnightMoves(int x, int y) {
if(!x && !y) return 0;
int dx[8]{1, 2, 2, 1, -1, -2, -2, -1}, dy[8]{-2, -1, 1, 2, 2, 1, -1, -2}, res = 0;
x = abs(x), y = abs(y);
set<pair<int, int>> s;
queue<pair<int, int>> q;
s.insert({0, 0});
q.push({0, 0});
while(!q.empty()) {
res++;
int sz = q.size();
while(sz--) {
auto p = q.front();
q.pop();
for(int i = 0; i < 8; i++) {
int nx = p.second + dx[i], ny = p.first + dy[i];
if(nx == x && ny == y) return res;
if(ny < -10 || nx < -10 || s.count({ny, nx})) continue;
s.insert({ny, nx});
q.push({ny, nx});
}
}
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/05/PS/LeetCode/minimum-knight-moves/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.