On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).
A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.
Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.
The knight continues moving until it has made exactly k moves or has moved off the chessboard.
Return the probability that the knight remains on the board after it has stopped moving.
Example 1:
Input: n = 3, k = 2, row = 0, column = 0
Output: 0.06250
Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on the board.
The total probability the knight stays on the board is 0.0625.
Example 2:
Input: n = 1, k = 0, row = 0, column = 0
Output: 1.00000
Problem summary: On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly k moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
3
2
0
0
Example 2
1
0
0
0
Related Problems
Out of Boundary Paths (out-of-boundary-paths)
Maximum Number of Moves to Kill All Pawns (maximum-number-of-moves-to-kill-all-pawns)
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #688: Knight Probability in Chessboard
class Solution {
public double knightProbability(int n, int k, int row, int column) {
double[][][] f = new double[k + 1][n][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
f[0][i][j] = 1;
}
}
int[] dirs = {-2, -1, 2, 1, -2, 1, 2, -1, -2};
for (int h = 1; h <= k; ++h) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
for (int p = 0; p < 8; ++p) {
int x = i + dirs[p], y = j + dirs[p + 1];
if (x >= 0 && x < n && y >= 0 && y < n) {
f[h][i][j] += f[h - 1][x][y] / 8;
}
}
}
}
}
return f[k][row][column];
}
}
// Accepted solution for LeetCode #688: Knight Probability in Chessboard
func knightProbability(n int, k int, row int, column int) float64 {
f := make([][][]float64, k+1)
for h := range f {
f[h] = make([][]float64, n)
for i := range f[h] {
f[h][i] = make([]float64, n)
for j := range f[h][i] {
f[0][i][j] = 1
}
}
}
dirs := [9]int{-2, -1, 2, 1, -2, 1, 2, -1, -2}
for h := 1; h <= k; h++ {
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
for p := 0; p < 8; p++ {
x, y := i+dirs[p], j+dirs[p+1]
if x >= 0 && x < n && y >= 0 && y < n {
f[h][i][j] += f[h-1][x][y] / 8
}
}
}
}
}
return f[k][row][column]
}
# Accepted solution for LeetCode #688: Knight Probability in Chessboard
class Solution:
def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
f = [[[0] * n for _ in range(n)] for _ in range(k + 1)]
for i in range(n):
for j in range(n):
f[0][i][j] = 1
for h in range(1, k + 1):
for i in range(n):
for j in range(n):
for a, b in pairwise((-2, -1, 2, 1, -2, 1, 2, -1, -2)):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n:
f[h][i][j] += f[h - 1][x][y] / 8
return f[k][row][column]
// Accepted solution for LeetCode #688: Knight Probability in Chessboard
impl Solution {
pub fn knight_probability(n: i32, k: i32, row: i32, column: i32) -> f64 {
let n = n as usize;
let k = k as usize;
let mut f = vec![vec![vec![0.0; n]; n]; k + 1];
for i in 0..n {
for j in 0..n {
f[0][i][j] = 1.0;
}
}
let dirs = [-2, -1, 2, 1, -2, 1, 2, -1, -2];
for h in 1..=k {
for i in 0..n {
for j in 0..n {
for p in 0..8 {
let x = i as isize + dirs[p];
let y = j as isize + dirs[p + 1];
if x >= 0 && x < n as isize && y >= 0 && y < n as isize {
let x = x as usize;
let y = y as usize;
f[h][i][j] += f[h - 1][x][y] / 8.0;
}
}
}
}
}
f[k][row as usize][column as usize]
}
}
// Accepted solution for LeetCode #688: Knight Probability in Chessboard
function knightProbability(n: number, k: number, row: number, column: number): number {
const f = Array.from({ length: k + 1 }, () =>
Array.from({ length: n }, () => Array(n).fill(0)),
);
for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
f[0][i][j] = 1;
}
}
const dirs = [-2, -1, 2, 1, -2, 1, 2, -1, -2];
for (let h = 1; h <= k; ++h) {
for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
for (let p = 0; p < 8; ++p) {
const x = i + dirs[p];
const y = j + dirs[p + 1];
if (x >= 0 && x < n && y >= 0 && y < n) {
f[h][i][j] += f[h - 1][x][y] / 8;
}
}
}
}
}
return f[k][row][column];
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(k × n^2)
Space
O(k × n^2)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.