Difficulty: Medium

Related Topics: Dynamic Programming

On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. 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.

688. Knight Probability in Chessboard - 图1

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: 3, 2, 0, 0
  2. Output: 0.0625
  3. Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
  4. From each of those positions, there are also two moves that will keep the knight on the board.
  5. The total probability the knight stays on the board is 0.0625.

Note:

  • N will be between 1 and 25.
  • K will be between 0 and 100.
  • The knight always initially starts on the board.

Solution

Language: Java

class Solution {
    private static int[][] moves = {{1, 2}, {-1, 2}, {1, -2}, {-1, -2},
                                    {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};
    private Double[][][] memo;

    public double knightProbability(int N, int K, int r, int c) {
        memo = new Double[K + 1][N][N];
        return dp(N, K, r, c);
    }

    // 定义:knight 从 (r,c) 开始移动 k 步后,它在留在棋盘内的概率
    private double dp(int N, int K, int r, int c) {
        // 出口
        // 1. knight 跳出棋盘,那么它留在棋盘内的概率为0(不可能事件)
        if (r < 0 || r >= N || c < 0 || c >= N) return 0;
        // 2. 这是一个非法的参数,概率为0(不可能事件)
        if (K < 0) return 0;
        // 3. knight 不移动,那么它留在棋盘内的概率为1(必然事件)
        if (K == 0) return 1;

        if (memo[K][r][c] != null) return memo[K][r][c];

        double p = 0;

        // 每次可以有 8 次移动机会
        for (int[] move : moves) {
            // 每次移动一次的概率是 1/8 = 0.124
            p += 0.125 * dp(N, K - 1, r + move[0], c + move[1]);
        }

        return memo[K][r][c] = p;
    }
}