October 10, 2019

688. Knight Probability in Chessboard

688. Knight Probability in Chessboard

三维 DP,可降为二维。Time = O(N^2 * K), Space = O(N^2)

class Solution {
    public double knightProbability(int N, int K, int r, int c) {
        double[][] dp0 = new double[N][N];
        dp0[r][c] = 1.0;
        int[][] dirs = {`{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2}, {-1, -2}, {-2, 1}, {-2, -1}`};
        for (int k = 0; k < K; k++) {
            double[][] dp1 = new double[N][N];
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    for (int m = 0; m < 8; m++) {
                        int x = i + dirs[m][0];
                        int y = j + dirs[m][1];
                        if (x < 0 || y < 0 || x >= N || y >= N) {
                            continue;
                        }
                        dp1[i][j] += dp0[x][y];
                    }
                }
            }
            dp0 = dp1;
        }
        
        double total = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                total += dp0[i][j];
            }
        }
        
        return total / Math.pow(8, K);
    }
}
comments powered by Disqus