AlgoMaster Logo

Knight Probability in Chessboard

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Recursive Approach

In this approach, we use recursion to explore all possible moves of the knight and calculate the probability of staying within the boundaries of the chessboard. The knight has 8 possible moves from any position, and we simulate every possible sequence of moves from the starting position for k steps.

Intuition:

  • Start at the initial position and make all possible moves recursively.
  • For each move, check if the new position is still inside the board.
  • If it's inside, recursively explore the next move.
  • Base case: If no more moves (k becomes zero), we've successfully completed a sequence.

Code:

2. Memoization Approach

We use memoization to optimize the recursive approach by storing the already computed probabilities for certain positions with given steps. This prevents recalculating probabilities for the same state, significantly reducing the number of computations.

Intuition:

  • Use a 3D array to save the probability results for position (i, j) with k moves remaining.
  • If the probability has been calculated for a specific state, reuse it instead of recalculating.

Code:

3. Dynamic Programming Approach

This approach uses a bottom-up dynamic programming table where dp[i][j][k] represents the probability of the knight being at position (i, j) with k moves remaining. We build the solution from the ground up.

Intuition:

  • Initialize the base case (when k=0).
  • Each position at step k is derived from the probabilities at step k-1.
  • Sum up all probabilities when k=0.

Code: