AlgoInsight

DSA problem

Minimum Knight Moves

MediumBreadth First Search (BFS)Pattern: Breadth First Search (BFS)top600AmazonGoogleMicrosoftAppleBloomberg

In an infinite chess board with coordinates from -infinity to +infinity, a knight starts at the square (0, 0) and wants to reach the square (x, y). A knight can move to any of 8 L-shaped squares relative to its current position: (+/-1, +/-2) and (+/-2, +/-1). Return the minimum number of moves to reach (x, y).

Because every move costs the same (one), the shortest path on this infinite grid is exactly the BFS distance. The complication is that the board is unbounded, so we must shrink the search space.

Two symmetries help. First, the knight's move pattern is invariant under reflection across both axes, so the minimum number of moves from (0, 0) to (x, y) equals the minimum from (0, 0) to (|x|, |y|). We can take absolute values up front and only search the first quadrant.

Second, we never need to wander far into negative coordinates, but the knight may briefly visit (-1, -1) or (-2, -2) near the origin on optimal paths to small targets, so we keep a small negative buffer when restricting the search to non-negative coordinates. With this, BFS visits O((x + y)^2) cells in the worst case and uses a hash set for visited squares, giving an overall O(max(x, y)^2) time and space.

Examples

Example 1
Input: x = 2, y = 1
Output: 1
Explanation: The knight reaches (2,1) in a single move from (0,0).
Example 2
Input: x = 5, y = 5
Output: 4
Explanation: A 4-move sequence such as (0,0) -> (2,1) -> (4,2) -> (3,4) -> (5,5) reaches the target.
Example 3
Input: x = 0, y = 0
Output: 0
Explanation: The starting square is already the target; zero moves are required.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bfsgraphshortest-path

Browse all DSA problems