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.
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.
Input: n = 1, k = 0, row = 0, column = 0
Output: 1.00000
1 <= n <= 250 <= k <= 1000 <= row, column <= n - 1In 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.
k becomes zero), we've successfully completed a sequence.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.
(i, j) with k moves remaining.(i, j, k) is computed once.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.
k is derived from the probabilities at step k-1.