#688

Knight Probability in Chessboard

Medium
Dynamic ProgrammingDynamic ProgrammingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(8^k)
O(n^2 * k)
Space
O(k)
O(n^2)
💡

Intuition

Time O(n^2 * k)Space O(n^2)

The optimal solution uses dynamic programming to store the probabilities of the knight being on the board after each move. This avoids redundant calculations and significantly reduces the time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a 3D DP array where dp[moves][r][c] represents the probability of the knight being at (r, c) after 'moves' moves.
  2. 2Step 2: Initialize dp[0][row][column] = 1, as the knight starts at the given position with 100% probability.
  3. 3Step 3: Iterate through each move from 1 to k, updating the DP table based on the possible knight moves.
solution.py12 lines
1def knightProbability(n, k, row, column):
2    moves = [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)]
3    dp = [[[0] * n for _ in range(n)] for _ in range(k + 1)]
4    dp[0][row][column] = 1
5    for moves_left in range(1, k + 1):
6        for r in range(n):
7            for c in range(n):
8                for dr, dc in moves:
9                    nr, nc = r + dr, c + dc
10                    if 0 <= nr < n and 0 <= nc < n:
11                        dp[moves_left][nr][nc] += dp[moves_left - 1][r][c] / 8
12    return sum(dp[k][r][c] for r in range(n) for c in range(n))

Complexity note: The time complexity is O(n^2 * k) because we iterate through each cell on the board for each of the k moves. The space complexity is O(n^2) due to the DP table storing probabilities for each cell.

  • 1Dynamic programming can significantly reduce redundant calculations.
  • 2Understanding the knight's movement is crucial for setting up the problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.