An interactive visualization of BFS on a chess board. Watch the wavefront expand as a knight explores all reachable squares level by level, finding the shortest path to any target coordinate.
BFS LeetCode 1197 ↗ Medium-infinity to +infinity,
you have a knight at square [0, 0].[x, y].
It is guaranteed the answer exists.
fun minKnightMoves(x: Int, y: Int): Int { val ax = Math.abs(x); val ay = Math.abs(y) // symmetry val queue = ArrayDeque<Triple<Int, Int, Int>>() queue.add(Triple(0, 0, 0)) val visited = mutableSetOf(Pair(0, 0)) val moves = arrayOf( intArrayOf(-2,-1),intArrayOf(-2,1),intArrayOf(-1,-2),intArrayOf(-1,2), intArrayOf(1,-2),intArrayOf(1,2),intArrayOf(2,-1),intArrayOf(2,1)) while (queue.isNotEmpty()) { val (cx, cy, steps) = queue.removeFirst() if (cx == ax && cy == ay) return steps for (m in moves) { val nx = cx + m[0]; val ny = cy + m[1] if (Pair(nx, ny) !in visited && nx >= -2 && ny >= -2) { visited.add(Pair(nx, ny)) queue.add(Triple(nx, ny, steps + 1)) } } } return -1}
A knight on an infinite chess board can reach any square. Since every knight move is "cost 1" (unweighted graph), BFS guarantees the shortest path. Each BFS level represents one additional knight move, so the first time we reach the target, we have found the minimum number of moves.
Because a knight's moves are symmetric in all four quadrants, we can map the target to the
first quadrant using x, y = abs(x), abs(y). This reduces the search space dramatically.
We allow a small negative buffer (nx >= -2, ny >= -2) because some shortest paths
briefly dip into negative coordinates (e.g., reaching (1,1) requires 4 moves, passing through negative territory).
x, y = abs(x), abs(y).
The BFS explores an area roughly proportional to the square of the distance to the target.
With the symmetry optimization, we only explore the first quadrant (plus a small buffer),
which keeps the search manageable. The answer itself is approximately max(|x|, |y|) / 2 moves
for large values, but the exact formula depends on the parity and relative values of x and y.