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:
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.
Example 2:
Input: n = 1, k = 0, row = 0, column = 0
Output: 1.00000
Constraints:
1 <= n <= 25
0 <= k <= 100
0 <= row, column <= n - 1
Solutions
Solution 1: Dynamic Programming
Let $f[h][i][j]$ denotes the probability that the knight is still on the chessboard after $h$ steps starting from the position $(i, j)$. Then the final answer is $f[k][row][column]$.
When $h = 0$, the knight is always on the chessboard, so $f[0][i][j] = 1$.
When $h \gt 0$, the probability that the knight is on the position $(i, j)$ can be transferred from the probability on its $8$ adjacent positions, which are:
where $(a, b)$ is one of the $8$ adjacent positions.
The final answer is $f[k][row][column]$.
The time complexity is $O(k \times n^2)$, and the space complexity is $O(k \times n^2)$. Here $k$ and $n$ are the given steps and the chessboard size, respectively.
constDIR:[(i32,i32);8]=[(-2,-1),(2,-1),(-1,-2),(1,-2),(2,1),(-2,1),(1,2),(-1,2),];constP:f64=1.0/8.0;implSolution{#[allow(dead_code)]pubfnknight_probability(n:i32,k:i32,row:i32,column:i32)->f64{// Here dp[i][j][k] represents through `i` steps, the probability that the knight stays on the board// Starts from row: `j`, column: `k`letmutdp:Vec<Vec<Vec<f64>>>=vec![vec![vec![0asf64;nasusize];nasusize];kasusize+1];// Initialize the dp vector, since dp[0][j][k] should be 1forjin0..nasusize{forkin0..nasusize{dp[0][j][k]=1.0;}}// Begin the actual dp processforiin1..=k{forjin0..n{forkin0..n{for(dx,dy)inDIR{letx=j+dx;lety=k+dy;ifSelf::check_bounds(x,y,n,n){dp[iasusize][jasusize][kasusize]+=P*dp[(iasusize)-1][xasusize][yasusize];}}}}}dp[kasusize][rowasusize][columnasusize]}#[allow(dead_code)]fncheck_bounds(i:i32,j:i32,n:i32,m:i32)->bool{i>=0&&i<n&&j>=0&&j<m}}