Knight Probability in Chessboard
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:
Example 2:
Constraints:
1 <= n <= 25
0 <= k <= 100
0 <= row, column <= n - 1
Solutions
This problem can be solved using dynamic programming. The idea is to keep track of the probability of reaching each cell after a certain number of moves. We start with the initial cell and for each move, we distribute its probability to all the reachable cells. After all moves, we sum up the probabilities of all cells to get the final result.
Approach -BFS
The problem can also be solved using Breadth-First Search (BFS). The idea is to start from the initial cell and for each cell, we calculate the probability of reaching it from all its reachable cells. We continue this process until we have made all the moves. The final result is the sum of the probabilities of all cells after k moves.
The time and space complexity of the given algorithm is as follows:
Time Complexity: The time complexity of this algorithm is O(n^2 * k). Here,
n
is the size of the chessboard andk
is the number of moves. This is because for each move, we are exploring 8 possible moves for each cell in then x n
chessboard.Space Complexity: The space complexity of this algorithm is also O(n^2 * k). This is due to the 3D memoization array that we are using to store the computed probabilities for each cell for a given number of moves. The size of this 3D array is
n x n x k
.
Last updated