Knight Probability in Chessboard — LeetCode 688 Python Solution

MediumDynamic Programming
Problem
#688
Reading time
3 min

The problem

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).

Example

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.

Python solution

Python
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]

Complexity

MeasureComplexity
TimeO(k \times n^2)
SpaceO(k \times n^2) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 688. Knight Probability in Chessboard is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 688. Knight Probability in Chessboard?
LeetCode 688. Knight Probability in Chessboard is rated Medium on LeetCode.
What is the time complexity of LeetCode 688. Knight Probability in Chessboard?
The Python solution on this page runs in O(k \times n^2).
What is the space complexity of LeetCode 688. Knight Probability in Chessboard?
The Python solution on this page uses O(k \times n^2) auxiliary space.
What topics does LeetCode 688. Knight Probability in Chessboard cover?
LeetCode 688. Knight Probability in Chessboard is tagged Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview