Minimum Knight Moves

35 min · minKnightMoves()

A knight ignores the streets between squares. It jumps in an L, lands, and asks the same question again: what's the fewest number of jumps from home to here?

A knight starts at (0, 0) on an infinite chessboard. Given integer coordinates (x, y), return the minimum number of knight moves needed to land there.

Each move changes position by one of these eight offsets:

  • (±2, ±1), or
  • (±1, ±2).

The signs are independent, so all four direction combinations count. The board has no edges or blocked squares, and reaching (0, 0) takes 0 moves.

Constraints

  • -300 <= x <= 300
  • -300 <= y <= 300
  • x and y are integers.

Hints

Search by move count

From the origin, generate every square reachable in one move, then two moves, then three. The first time you see the target gives the minimum.

The board repeats itself

Reflecting a route across either axis, or swapping its coordinates, doesn't change its length. You only need to solve for x >= y >= 0.

Keep a small safety margin

A shortest route may briefly step past an axis, especially near the origin. Allow coordinates down to -2, and stop exploring more than two squares past the folded target.

Follow-up

Could a search starting from both the origin and the target reduce the number of board states you visit for faraway coordinates?

Visible cases

Examples

Example 1

ready
Input
x = 2
y = 1
Expected
1
Why
(2, 1) is one legal knight jump

Example 2

ready
Input
x = 5
y = 5
Expected
4
Why
no route uses fewer than four jumps

Example 3

ready
Input
x = 0
y = 0
Expected
0
Why
the knight already occupies the target

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite