AlgoViz

Minimum Knight Moves

Medium

BFS over an unweighted move graph

Problem

On an infinite chessboard, return the minimum number of knight moves to go from (0,0) to a target (x,y).

In simple words

BFS the chessboard: every knight hop is one step, so the first time you reach the target is shortest.

The idea

Every knight move costs the same, so the fewest moves is a shortest path in an unweighted graph and BFS finds it. The board is infinite, so exploit the symmetry: fold the target into one quadrant and bound the search just past it.

The trick

  • BFS gives the shortest path only because every edge has equal weight.
  • Use |x| and |y| — the answer is symmetric across both axes.
  • Keep a visited set; without it the branching factor of 8 explodes immediately.
R
F
F
F
F
·
·
F
F
minute0
fresh6

Step 1 of 6. Every rotten orange (R) rots its fresh (F) neighbours each minute — a multi-source BFS. minute 0, fresh 6.

1/6
Optimal
timeO(rows·cols)spaceO(rows·cols)

All sources start at minute 0.

1// enqueue all rotten cells; BFS by layers,2// converting fresh neighbors, counting minutes.3while (q.length && fresh > 0) {4  minutes++;5  for (let n = q.length; n > 0; n--) spread(q.shift());6}7return fresh === 0 ? minutes : -1;

Input

grid
3 × 3

Memory

minute
0
fresh
6

Output

minute
0
fresh
6
answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
x = 2, y = 1
Output:
1
Explanation:
A knight reaches (2,1) in one hop.

Example 2

Input:
x = 5, y = 5
Output:
4
Explanation:
The nearest square (5,5) takes 4 hops.

Example 3

Input:
x = 0, y = 0
Output:
0
Explanation:
Already there → 0.

Finished the walkthrough? Add it to your streak.