Minimum Knight Moves - Problem

In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].

A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists.

The 8 possible knight moves are: [+2,+1], [+2,-1], [-2,+1], [-2,-1], [+1,+2], [+1,-2], [-1,+2], [-1,-2].

Input & Output

Example 1 — Basic Case
$ Input: x = 2, y = 1
Output: 1
💡 Note: Knight can reach (2,1) from (0,0) in 1 move: (0,0) → (2,1)
Example 2 — Multiple Steps
$ Input: x = 5, y = 5
Output: 4
💡 Note: One optimal path: (0,0) → (2,1) → (4,2) → (5,4) → (5,5) in 4 moves
Example 3 — Negative Coordinates
$ Input: x = -3, y = -3
Output: 2
💡 Note: Using symmetry, same as reaching (3,3): (0,0) → (2,1) → (3,3) in 2 moves

Constraints

  • |x| + |y| ≤ 300

Visualization

Tap to expand
Minimum Knight Moves - BFS with Symmetry INPUT -2 -1 0 1 2 K T x = 2 y = 1 Start: [0,0] Target: [2,1] Infinite chess board ALGORITHM STEPS 1 Use Symmetry Convert to |x|, |y| 2 Initialize BFS Queue: [(0,0,0)] 3 Explore 8 Moves L-shaped jumps 4 Check Target Return steps if found BFS Queue Processing (0,0) --> (2,1) OK 8 moves: (+/-1,+/-2), (+/-2,+/-1) Visited set prevents cycles Bound: -2 to max(x,y)+2 FINAL RESULT K (0,0) T (2,1) OUTPUT 1 Minimum Steps: 1 Move Explanation From (0,0): +2 in x, +1 in y = (2,1) in 1 step Key Insight: BFS guarantees minimum steps in unweighted graphs. Symmetry optimization: knight moves are symmetric, so we can work with absolute values |x|, |y|. Bounding the search space to [-2, max+2] prevents infinite exploration while allowing necessary "backwards" moves. Time: O(max(|x|,|y|)^2), Space: O(max(|x|,|y|)^2) TutorialsPoint - Minimum Knight Moves | Optimized BFS with Symmetry
Asked in
Amazon 35 Google 28 Microsoft 22 Facebook 18
28.5K Views
Medium Frequency
~25 min Avg. Time
842 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