Knight Probability in Chessboard

MediumProbability DP · Grid🧩 Probability DPLeetCode #688 ↗Updated

Problem

A knight starts on cell (row, column) of an n × n board and makes exactly k moves. Each move picks one of the 8 knight jumps uniformly at random, even if it leads off the board; once off, the knight stays off. Return the probability that it is still on the board after all k moves.
Inputn = 3, k = 2, row = 0, column = 0Output0.06250
Inputn = 1, k = 0, row = 0, column = 0Output1.00000

1 ≤ n ≤ 25  ·  0 ≤ k ≤ 100  ·  0 ≤ row, column < n  ·  answers within 10-5 are accepted

Try it yourself

Java
class Solution {
    public double knightProbability(int n, int k, int row, int column) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The probability of surviving depends only on (cell, moves left), not on the path that got there — so 8k paths collapse into k · n2 states, each the average of its 8 neighbours.
PatternProbability DP

Instinct Asked for a probability or expected value after random moves? Run DP over (step, state) and split each state's mass across every outcome.

Memory hack Pour the probability like water - split it across the moves, let what spills off the board drain away, and the puddle that's left is your answer.

Open the Probability DP guide →

Approaches

Brute ForcePlain Recursion over All Paths

Time O(8k)Space O(k)

P(r, c, k) = 0 if off the board, 1 if no moves are left, otherwise the average of P over the 8 jumps with k-1 moves. This literally explores every random path.

Java
private static final int[][] JUMPS =
    {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}};

public double knightProbability(int n, int k, int row, int column) {
    if (row < 0 || row >= n || column < 0 || column >= n) return 0.0;
    if (k == 0) return 1.0;
    double sum = 0;
    for (int[] j : JUMPS) {
        sum += knightProbability(n, k - 1, row + j[0], column + j[1]);
    }
    return sum / 8.0;
}

Matches the definition exactly, but blows up for k beyond ~10.

At a glance

LevelApproachTimeSpace
Brute ForcePlain Recursion over All PathsO(8k)O(k)
BetterTop-Down MemoisationO(k · n2)O(k · n2)
OptimalBottom-Up Probability Spreading (Two Grids)O(k · n2)O(n2)
Common pitfalls
  • Dividing by the number of valid moves instead of always by 8.
  • Letting a knight that left the board come back — off-board mass must be dropped.
  • Using float or integer counts of paths: 8100 overflows everything.
Interview tips
  • Write the recurrence first; memoisation then falls out naturally.
  • Point out the state is (cell, moves left) — the path history is irrelevant.
  • Mention rolling arrays to cut memory from O(k·n2) to O(n2).
Pattern
Probability DP on a grid → random moves for a fixed number of steps; each state is the average of its successors.
My notes saved in this browser