Minimum Knight Moves - Problem
Minimum Knight Moves

Imagine you're playing chess on an infinite chessboard that extends in all directions from -infinity to +infinity. Your knight starts at position [0, 0] and needs to reach a target square at coordinates [x, y].

A knight moves in an L-shape: exactly two squares in one cardinal direction (north, south, east, or west), then one square perpendicular to that direction. This gives the knight 8 possible moves from any position.

Goal: Find the minimum number of moves required for the knight to travel from [0, 0] to [x, y].

The key insight is that this is a shortest path problem on an infinite grid, where each position is a node and knight moves are the edges.

Input & Output

example_1.py โ€” Basic Case
$ Input: x = 2, y = 1
โ€บ Output: 1
๐Ÿ’ก Note: The knight can reach [2,1] in exactly 1 move from [0,0]. This is one of the 8 possible knight moves: 2 squares right, 1 square up.
example_2.py โ€” Multiple Steps
$ Input: x = 5, y = 5
โ€บ Output: 4
๐Ÿ’ก Note: One optimal path: [0,0] โ†’ [2,1] โ†’ [4,2] โ†’ [3,4] โ†’ [5,5]. The knight needs exactly 4 moves to reach [5,5].
example_3.py โ€” Origin Case
$ Input: x = 0, y = 0
โ€บ Output: 0
๐Ÿ’ก Note: The knight is already at the target position [0,0], so no moves are needed.

Visualization

Tap to expand
STARTTARGETBFS Level-by-Level Exploration๐ŸŽฏ Each level explores all positions reachable in exactly k moves
Understanding the Visualization
1
Initialize
Knight starts at origin [0,0] with 0 moves taken
2
Level 1 Exploration
Explore all 8 positions reachable in exactly 1 knight move
3
Level 2 Exploration
From each Level 1 position, explore all reachable positions in 1 more move
4
Continue Until Target
Keep expanding level by level until target is found
5
Shortest Path Found
The first time we reach target guarantees minimum moves
Key Takeaway
๐ŸŽฏ Key Insight: BFS explores positions in order of distance from start, guaranteeing the first path found to any position is the shortest possible.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(max(|x|, |y|)ยฒ)

BFS explores positions in a roughly circular pattern around the origin, with radius proportional to the distance to target

n
2n
โœ“ Linear Growth
Space Complexity
O(max(|x|, |y|)ยฒ)

Space needed for queue and visited set, which store all explored positions

n
2n
โœ“ Linear Space

Constraints

  • |x| + |y| โ‰ค 300
  • -300 โ‰ค x, y โ‰ค 300
  • The answer is guaranteed to exist
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18 Apple 15
52.0K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen