Fewest knight moves
Standard · Write code · about 15 min
A knight starts on square (0, 0) of an n × n board. Return the fewest jumps it needs to land on square (r, c), or -1 if it cannot get there.
A jump moves two squares in one direction and one square in the other, and the knight must stay on the board.
Example 1
Input:
[5,4,0]
Output:
2
Two jumps: (0, 0) → (2, 1) → (4, 0).
Example 2
Input:
[3,1,1]
Output:
-1
The center of a 3 × 3 board cannot be reached.
Constraints
- 1 ≤ n ≤ 30
- 0 ≤ r, c < n
Learn the idea first: Implicit graphs: grids, states and puzzles, a visual lesson.
More Implicit graphs: grids, states and puzzles problems
- Neighbors of a cell Warm-up
- Count islands preview Warm-up
- Knight moves Standard
- Fewest operations Standard
- Model a puzzle as a graph Challenge