Minimum Knight Moves

Medium

Topics
BFSMath

On an infinite chessboard with coordinates from -infinity to +infinity, a knight starts at square [0, 0].

A knight has 8 possible moves: it moves two squares in one cardinal direction and then one square in a perpendicular direction.

Return the minimum number of moves needed to reach the square [a, b]. It is always possible.

The target is named a and b here because that is what the judge calls the two arguments; LeetCode calls them x and y.

Example 1

2·1·1·11···T0··S··-11···1-2·1·1·-2-1012
S the start, T the targetreachable in one move
A knight moves two squares along one axis and one along the other, giving the eight marked squares from any position — never a diagonal step, which is why a square touching the start corner is not one move away. The target is among them, so the answer is 1. The board is infinite in every direction, so moving away from the target is allowed.
Column headings are x, row headings are y, with y increasing upwards.
Input:  a = 2, b = 1
Output: 1
Explanation: A single knight move reaches [2,1] from the origin.

Example 2

5·······T4········3········2·1·1····11···1···0··S·····-11···1···-2·1·1····-2-1012345
S the start, T the targetreachable in one move
The target is not among them; reaching (5, 5) takes 4 moves.
Input:  a = 5, b = 5
Output: 4
Explanation: No three moves reach [5,5]; four do.

Example 3

2·1·1·11···10··S=T··-11···1-2·1·1·-2-1012
S=T, the start and the targetreachable in one move
Start and target are the same square, so no move is needed and the answer is 0.
Input:  a = 0, b = 0
Output: 0
Explanation: The knight is already there.

Example 4

2·1·1·11··T10··S··-11···1-2·1·1·-2-1012
S the start, T the targetreachable in one move
Input:  a = 1, b = 1
Output: 2
Explanation: A diagonal neighbour is two moves away, not one — the knight cannot step diagonally.

Constraints

  • -300 <= a, b <= 300
  • 0 <= |a| + |b| <= 300
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every move costs the same, so the shortest sequence is a shortest path in an unweighted graph whose vertices are squares. On an infinite board the graph is infinite, which is the only real obstacle — the search has to be fenced in somehow.

Two observations do the fencing. The board is symmetric under reflection in both axes and under swapping the axes, so a target in any quadrant can be folded into the first by taking absolute values; the answer is unchanged. And a shortest path never needs to wander far outside the rectangle between the origin and the target — a small margin is enough, because any excursion further out has to be walked back.

With a bounded region the search is an ordinary breadth-first expansion, which is what guarantees the minimum: squares are reached in order of distance, so the first time the target is dequeued is on a shortest path.

Approach

  1. Fold the target into the first quadrant by taking absolute values of both coordinates. Reflections do not change the move count.
  2. Breadth-first search from (0, 0), expanding all 8 knight moves from each square.
  3. Confine the search to squares with both coordinates between -2 and the target coordinate plus 2. The margin allows the small overshoot that near-axis targets need — reaching (1, 1) requires stepping to a negative coordinate or past the target.
  4. Mark squares as seen when enqueued, not when dequeued, so no square joins the frontier twice.
  5. Return the distance recorded when the target is first reached.

Walkthrough

a = 1, b = 1   (already in the first quadrant)
search box: -2 .. 3 on both axes

distance 0   (0,0)

distance 1   the eight moves from the origin
             (2,1) (1,2) (-1,2) (-2,1) (-2,-1) (-1,-2) (1,-2) (2,-1)
             the target is not among them

distance 2   expanding that frontier, one square reaches it:
             from (-1,2) by (+2,-1)  ->  (1,1)   found

answer 2

The only two-move routes to (1,1) pass through a square with a
negative coordinate, which is why the box extends to -2 rather
than stopping at the origin.

Complexity

  • Time — O(a * b): the search visits each square of the bounded box at most once, and the box is proportional to the target coordinates.
  • Space — O(a * b): the seen set and the queue, both bounded by the box.

Common Pitfalls

  • Searching the unbounded board. Without a box the frontier grows for ever on an unreachable-looking target, and even on a reachable one it explores far more squares than it needs.
  • Making the box exactly the rectangle from the origin to the target. Targets near an axis need to step outside it — (1, 1) is unreachable without visiting a negative coordinate — so the answer comes back wrong or not at all.
  • Marking a square seen when it is dequeued rather than when it is enqueued. The same square then enters the queue from several neighbours, which is correct but much slower.
  • Trying a greedy or closed-form rule based on |a| + |b|. It works for most targets and fails on the small ones near the origin and the axes, which is exactly where the test cases concentrate.

Full Solution — all languages

class Solution:
    def minKnightMoves(self, a, b):
        from collections import deque
        x, y = abs(a), abs(b)
        if x == 0 and y == 0:
            return 0
        MOVES = ((1, 2), (2, 1), (2, -1), (1, -2),
                 (-1, -2), (-2, -1), (-2, 1), (-1, 2))
        seen = {(0, 0)}
        q = deque([(0, 0, 0)])
        while q:
            cx, cy, steps = q.popleft()
            if cx == x and cy == y:
                return steps
            for dx, dy in MOVES:
                nx, ny = cx + dx, cy + dy
                if -2 <= nx <= x + 2 and -2 <= ny <= y + 2 and (nx, ny) not in seen:
                    seen.add((nx, ny))
                    q.append((nx, ny, steps + 1))
        return -1
SensAI
Beta
Tap the mic to stop voice mode