1197. Minimum Knight Moves
Asked at 12Apple30Meta28Google23Microsoft20Amazon13eBay53Waymo67Databricks44Nvidia39Uber30LinkedIn27Oracle27
Problem
On an infinite chessboard a knight starts at [0, 0]. Return the minimum number of knight moves to reach [x, y] (always possible).
Example: x = 2, y = 1 → 1; x = 5, y = 5 → 4
Constraints: |x| + |y| ≤ 300.
Problem (Premium): on an infinite chessboard a knight starts at (0, 0). Return the minimum number of moves to reach (x, y) (|x| + |y| ≤ 300).
BFS over squares. Two prunings make it fast: the board is symmetric, so solve for (|x|, |y|); and an optimal path never needs to go more than 2 squares beyond the box [0, x] × [0, y], so ignore squares outside [−2, x+2] × [−2, y+2].
Complexity: O(x · y).
class Solution:
def minKnightMoves(self, x: int, y: int) -> int:
x, y = abs(x), abs(y)
seen, q = {(0, 0)}, deque([(0, 0, 0)])
while q:
a, b, d = q.popleft()
if (a, b) == (x, y):
return d
for da, db in ((1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)):
na, nb = a + da, b + db
if -2 <= na <= x + 2 and -2 <= nb <= y + 2 and (na, nb) not in seen:
seen.add((na, nb))
q.append((na, nb, d + 1))
assert Solution().minKnightMoves(2, 1) == 1
assert Solution().minKnightMoves(5, 5) == 4
assert Solution().minKnightMoves(0, 0) == 0
assert Solution().minKnightMoves(1, 1) == 2
assert Solution().minKnightMoves(1, 0) == 3
assert Solution().minKnightMoves(-1, -2) == 1
assert Solution().minKnightMoves(300, 0) == 150
class Solution {
public int minKnightMoves(int x, int y) {
x = Math.abs(x); y = Math.abs(y);
int off = 2; // shift so coordinates >= -2 index from 0
boolean[][] seen = new boolean[x + 5][y + 5];
Deque<int[]> q = new ArrayDeque<>();
q.add(new int[]{0, 0});
seen[off][off] = true;
int[][] moves = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}};
for (int d = 0; ; d++) {
for (int i = q.size(); i > 0; i--) {
int[] p = q.poll();
if (p[0] == x && p[1] == y) return d;
for (int[] m : moves) {
int a = p[0] + m[0], b = p[1] + m[1];
if (a < -2 || b < -2 || a > x + 2 || b > y + 2 || seen[a + off][b + off]) continue;
seen[a + off][b + off] = true;
q.add(new int[]{a, b});
}
}
}
}
}
func minKnightMoves(x int, y int) int {
if x < 0 { // the board is symmetric
x = -x
}
if y < 0 {
y = -y
}
type state struct{ a, b int }
seen := map[state]bool{{0, 0}: true}
q := []state{{0, 0}}
for d := 0; len(q) > 0; d++ {
next := []state{}
for _, s := range q {
if s.a == x && s.b == y {
return d
}
for _, m := range [][2]int{{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}} {
n := state{s.a + m[0], s.b + m[1]}
if n.a >= -2 && n.a <= x+2 && n.b >= -2 && n.b <= y+2 && !seen[n] { // a small margin is enough
seen[n] = true
next = append(next, n)
}
}
}
q = next
}
return -1
}