leecode-骑士在棋盘上的概率 Kotlin

题目:力扣

思路:官方思路 

 

class Solution {
    fun knightProbability(N: Int, K: Int, r: Int, c: Int): Double {
        var currentMatrix = Array(N) { DoubleArray(N) {0.0} }
        var nextMatrix = Array(N) { DoubleArray(N) {0.0} }
        currentMatrix[r][c] = 1.0 
        var possibleMoveArr = arrayOf(
            arrayOf(-1, 2),
            arrayOf(1, 2),
            arrayOf(2, 1),
            arrayOf(2, -1),
            arrayOf(1, -2),
            arrayOf(-1, -2),
            arrayOf(-2, -1),
            arrayOf(-2, 1)
        ) 
        var result = 0.0
        
        for (k in 1..K) {
            for (i in 0 until N) {
                for (j in 0 until N) {
                    if (currentMatrix[i][j] != 0.0) {
                        var nextI = 0
                        var nextJ = 0
                        for (move in 0 until 8) {
                            nextI = i + possibleMoveArr[move][0]
                            nextJ = j + possibleMoveArr[move][1]
                            if (isMoveValid(nextI, nextJ, N)) {
                                nextMatrix[nextI][nextJ] += currentMatrix[i][j] / 8.0
                            }
                        }
                    }
                }
            }
            currentMatrix = nextMatrix
            nextMatrix = Array(N) { DoubleArray(N) {0.0} }
        }
        
        for (i in 0 until N) {
            for (j in 0 until N) {
                result += currentMatrix[i][j]
            }
        }
        
        return result
    }
    fun isMoveValid(nextI: Int, nextJ: Int, n: Int): Boolean {
        if (nextI >= 0 && nextJ >= 0 && nextI < n && nextJ < n) {
            return true
        } else {
            return false
        }
    }
}






class Solution {
    static int[][] dirs = {{-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}};


    public double knightProbability(int n, int k, int row, int column) {
        double[][][] dp = new double[k + 1][n][n];
        for (int step = 0; step <= k; step++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (step == 0) {
                        dp[step][i][j] = 1;
                    } else {
                        for (int[] dir : dirs) {
                            int ni = i + dir[0], nj = j + dir[1];
                            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {
                                dp[step][i][j] += dp[step - 1][ni][nj] / 8;
                            }
                        }
                    }
                }
            }
        }
        return dp[k][row][column];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值