Leetcode 刷題筆記: 688. Knight Probability in Chessboard (騎士跳出去的機率)

Leetcode 刷題筆記: 688. Knight Probability in Chessboard

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.


Constraints:

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

題目很清楚,給你一個knight開始的位置,然後開始跳,問k steps以後,騎士尚未離開board的機率

最簡單解法就是 定義 dp[i][j][k]成 在i,j位置 第k steps 有多少種跳法可以在i,j位置

邊界條件 dp[row][column][0]=1 之後走兩個迴圈
假設一開始在(r,c) 位置
有可能跳到r+dr, c+dc
dr, dc 為下面八種可能之一 如果沒超出即可更新。
(2,1),(2,-1),(-2,1),(-2,-1),(1,2),(1,-2),(-1,2),(-1,-2)

請參考下面python code








class Solution:
    def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
        dp = [[[0]*(k+1) for _ in range(n)] for _ in range(n)]
        dp[row][column][0] = 1
        
        for i in range(1,k+1):
            for r in range(n):
                for c in range(n):
                    for dr, dc in ((2,1),(2,-1),(-2,1),(-2,-1),(1,2),(1,-2),(-1,2),(-1,-2)): 
                        if 0 <= r + dr < n and 0 <= c + dc < n:
                            dp[r+dr][c+dc][i]+=dp[r][c][i-1]/8
        
        
        
        ans=0
        for i in range(n):
            for j in range(n):
                ans+=dp[i][j][k]
        
        return ans

留言

這個網誌中的熱門文章

1041. Robot Bounded In Circle 機器人在圈圈裏面?

382. Linked List Random Node: 隨機選元素從list裡面

2134. Minimum Swaps to Group All 1's Together II 使得所有1連在一起