Minimum Knight Moves - Problem
Minimum Knight Moves
Imagine you're playing chess on an infinite chessboard that extends in all directions from
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
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.
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
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
โ Linear Growth
Space Complexity
O(max(|x|, |y|)ยฒ)
Space needed for queue and visited set, which store all explored positions
โ Linear Space
Constraints
- |x| + |y| โค 300
- -300 โค x, y โค 300
- The answer is guaranteed to exist
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code