Knight Probability in Chessboard:棋盘上计算K步之后棋子仍在棋盘上的概率

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.

《Knight Probability in Chessboard:棋盘上计算K步之后棋子仍在棋盘上的概率》

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:

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:

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

思路:动态规划

f[r][c][steps]=dr,dcf[r+dr][c+dc][steps1]/8.0

dr,dc表示所有和里的移动,f[r][c][steps]表示位置是r、c第steps步可能的概率  

每次只计算当前一步和下一步,所以用二维数组即可。计算棋盘上所有点在本轮可能被访问的概率。最后棋盘上所有点求和就是仍在棋盘上的概率。

时间复杂度O(KN^2) 因为if所在的循环是常数级。

空间复杂度O(N^2)

class Solution {
    public double knightProbability(int N, int K, int r, int c) {
        double[][] d = new double[N][N];
        int[] R = {2,2,-2,-2,1,1,-1,-1};
        int[] C = {1,-1,1,-1,2,-2,2,-2};
        d[r][c] = 1;
        for(int round = 0;round < K;round++){
            double[][] dtemp = new double[N][N];
            for(int i=0;i<N;i++){
                for(int j=0;j<N;j++){
                    for(int a = 0 ;a < 8; a++){
                        int rr = i + R[a];
                        int cc = j + C[a];
                        if(rr >= 0 && rr < N & cc >= 0 && cc < N){
                            dtemp[rr][cc] += d[i][j]/8;
                        }
                    }
                }
            }
            d = dtemp;
        }
        double result = 0; 
        for(int i = 0;i<N;i++){
            for(int j = 0;j<N;j++){
                result += d[i][j];
            }
        }
        return result;
    }
}
    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/u013300579/article/details/78413647
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞