LeetCode 688 Knight Probability in Chessboard (概率dp)

244 篇文章 0 订阅
177 篇文章 0 订阅

On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).

A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell 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 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: n = 3, k = 2, row = 0, column = 0
Output: 0.06250
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.

Example 2:

Input: n = 1, k = 0, row = 0, column = 0
Output: 1.00000

Constraints:

  • 1 <= n <= 25
  • 0 <= k <= 100
  • 0 <= row, column <= n

题目链接:https://leetcode.com/problems/knight-probability-in-chessboard/

题目大意:给一个n*n的棋盘,从(row, column)点开始跳k步,求最终棋子还在棋盘上的概率

题目分析:dp[i][j][kk]表示跳了kk步落在点(i,j)的概率,8个方向转移下即可,答案为dp[i][j][k]的和

8ms,时间击败76.58%

class Solution {
    
    final int[] dx = new int[] {-2, -1, 1, 2, -2, -1, 1, 2};
    final int[] dy = new int[] {-1, -2, 2, 1, 1, 2, -2, -1};
    
    public double knightProbability(int n, int k, int row, int column) {
        if (k == 0) {
            return 1.0;
        }
        double[][][] dp = new double[n][n][k + 1];
        dp[row][column][0] = 1.0;
        for (int kk = 1; kk <= k; kk++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    for (int p = 0; p < 8; p++) {
                        if (i + dx[p] >= 0 && i + dx[p] < n && j + dy[p] >= 0 && j + dy[p] < n) {
                            dp[i][j][kk] += dp[i + dx[p]][j + dy[p]][kk - 1] * 0.125;
                        }   
                    }
                    // System.out.println("dp["+i+"]["+j+"]["+kk+"] = " + dp[i][j][kk]);
                }
            }
        }
        double ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                ans += dp[i][j][k];
            }
        }
        return ans;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值