Leetcode
Dynamic Programming
688 Knight Probability in Chessboard

1. Question

On anNxNchessboard, a knight starts at ther-th row andc-th column and attempts to make exactlyKmoves. The rows and columns are 0 indexed, so the top-left square is(0, 0), and the bottom-right square is(N-1, N-1).
A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square 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 exactlyKmoves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.
Example:
1
Input: 3, 2, 0, 0
2
3
Output: 0.0625
4
5
Explanation:
6
There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
7
From each of those positions, there are also two moves that will keep the knight on the board.
8
The total probability the knight stays on the board is 0.0625.
Copied!
Note:
Nwill be between 1 and 25.Kwill be between 0 and 100.
The knight always initially starts on the board.

2. Implementation

(1) 3D DP
1
class Solution {
2
public double knightProbability(int N, int K, int r, int c) {
3
int[][] directions = {{-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}};
4
double [][][] dp = new double[K + 1][N][N];
5
6
for (int i = 0; i < N; i++) {
7
for (int j = 0; j < N; j++) {
8
dp[0][i][j] = 1;
9
}
10
}
11
12
for (int step = 1; step <= K; step++) {
13
for (int row = 0; row < N; row++) {
14
for (int col = 0; col < N; col++) {
15
double prob = 0.0;
16
17
for (int[] direction : directions) {
18
int nextRow = row + direction[0];
19
int nextCol = col + direction[1];
20
21
if (nextRow < 0 || nextRow >= N || nextCol < 0 || nextCol >= N) {
22
continue;
23
}
24
25
prob += dp[step - 1][nextRow][nextCol] / 8;
26
}
27
dp[step][row][col] = prob;
28
}
29
}
30
}
31
return dp[K][r][c];
32
}
33
}
Copied!

3. Time & Space Complexity

3D DP: 时间复杂度O(k*n^2),空间复杂度O(k*n^2)