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:

Input: 3, 2, 0, 0

Output: 0.0625

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.

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

class Solution {
    public double knightProbability(int N, int K, int r, int c) {
        int[][] directions = {{-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}};
        double [][][] dp = new double[K + 1][N][N];

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                dp[0][i][j] = 1;
            }
        }

        for (int step = 1; step <= K; step++) {
            for (int row = 0; row < N; row++) {
                for (int col = 0; col < N; col++) {
                    double prob = 0.0;

                    for (int[] direction : directions) {
                        int nextRow = row + direction[0];
                        int nextCol = col + direction[1];

                        if (nextRow < 0 || nextRow >= N || nextCol < 0 || nextCol >= N) {
                            continue;
                        }

                        prob += dp[step - 1][nextRow][nextCol] / 8;
                    }
                    dp[step][row][col] = prob;
                }
            }
        }
        return dp[K][r][c];
    }
}

3. Time & Space Complexity

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

Last updated