1. 程式人生 > >【LeetCode】688. Knight Probability in Chessboard 解題報告(Python)

【LeetCode】688. Knight Probability in Chessboard 解題報告(Python)

題目描述:

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.

此處輸入圖片的描述

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:

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

題目大意

有個N * N的棋盤,上面有個馬,馬走日字象走田嘛,找出這個馬走了K步之後依然在這個棋盤上的概率。

解題方法

如果dfs的話一定會超時的,所以還是得用dp來解。

這個dp陣列代表在某一輪中,這個馬能到這個位置的次數。

dp更新的策略是,我們遍歷棋盤的每個位置,當前的數值是能走到這個位置的在上一輪dp的數值 + 1。

這個題的對稱性讓這個題變得簡單而又有趣。最內層的for迴圈對dp進行更新的時候是不用考慮索引位置的,因為對稱性太美了。

時間複雜度是O(K * N ^ 2),空間複雜度是O(N ^ 2)。

注意,python2裡面的/預設的是地板除,需要用float再除得到概率。

程式碼如下:

class Solution(object):
    def knightProbability(self, N, K, r, c):
        """
        :type N: int
        :type K: int
        :type r: int
        :type c: int
        :rtype: float
        """
        dp = [[0 for i in range(N)] for j in range(N)]
        dp[r][c] = 1
        directions = [(1, 2), (1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1), (-1, 2), (-1, -2)]
        for k in range(K):
            new_dp = [[0 for i in range(N)] for j in range(N)]
            for i in range(N):
                for j in range(N):
                    for d in directions:
                        x, y = i + d[0], j + d[1]
                        if x < 0 or x >= N or y < 0 or y >= N:
                            continue
                        new_dp[i][j] += dp[x][y]
            dp = new_dp
        return sum(map(sum, dp)) / float(8 ** K)

參考資料:

日期

2018 年 9 月 17 日 —— 早上很涼,夜裡更涼