Skip to main content
medium

Minimum Knight Moves

A hopper starts on tile (0, 0) of an endless courtyard of square tiles. It jumps like a chess knight: two tiles along one axis and one tile along the other, in any of the eight directions, and each jump lands on a tile. Tile (x, y) is x tiles to the right and y tiles up from the start, and either number can be negative. Return the fewest jumps that land the hopper exactly on tile (x, y). Limits: -300 <= x <= 300, -300 <= y <= 300 and |x| + |y| <= 300. The answer is at most 151. Example: x = 3, y = 3 => 2 (0,0) -> (1,2) -> (3,3) Beware: x = 1, y = 0 is NOT one jump away; it takes 3.

A knight stands on the middle of an endless chessboard, and you want the fewest hops that land it on one particular square. Interviewers like it because the board has no walls to stop a search, so your first decision is how not to wander forever. The classic trap is clipping the search too tightly: the square right next to the start takes three hops, and the road there swings outside the box you drew. Targets stay within |x| <= 300, |y| <= 300 and |x| + |y| <= 300.

BFS / DFSMath & Geometry

Examples

You write

min_knight_moves(x: int, y: int)

  1. Example 1

    Input
    x = 3, y = 3
    returns
    2
  2. Example 2

    Input
    x = 0, y = 0
    returns
    0

Save this for your laptop

The editor and Run need a bigger screen. The link opens Minimum Knight Moves ready to code. It is free, and the editor needs no account.

The pattern behind it

BFS & DFS

I reach for it when

  • You walk a grid, a graph or a tree and visit each cell once.
  • The word shortest appears and every step costs the same.

Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.

All 52 BFS & DFS problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.

1Minimum Knight Movesmedium
Based onLeetCode

Get a note when something new lands

New company guides, new problems and big changes to Coco. Rare, and you can leave any time. By joining you agree to get these emails.