SDE & MLE Prep

1197. Minimum Knight Moves

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))