Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Minimum Knight Moves

LeetCode #1197Medium
BFS = shortest path on the move-graph

On an infinite chessboard with a knight starting at the origin, return the minimum number of knight moves needed to reach a given target square.

Asked atAmazonGoogle
step 1 / 47
6 × 6 board · knight from (0,0) to (4,4)
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
queue · cells to expand
front →
(empty)
← back
BFS over knight moves
1queue = [start]; dist(start) = 0
2while queue not empty:
3 cell = queue.dequeue()
4 if cell == target: return dist(cell)
5 for each of the 8 knight moves:
6 if neighbour in bounds and unvisited:
7 dist = dist(cell) + 1; enqueue it
8return -1 // unreachable
state
  • start(0,0)
  • target(4,4)

line 1Minimum Knight Moves: a knight starts at (0,0) and we want the fewest L-shaped hops to reach (4,4). The key insight: treat each square as a graph node whose neighbours are the (up to) 8 squares one knight-move away. On an UNWEIGHTED graph, BFS finds shortest paths — so the BFS layer at which (4,4) first appears is exactly the minimum number of moves.