1. 程式人生 > >【LeetCode】576. Out of Boundary Paths 解題報告(Python)

【LeetCode】576. Out of Boundary Paths 解題報告(Python)

目錄

題目描述

There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, you can move the ball to adjacent cell or cross the grid boundary in four directions (up, down, left, right). However, you can at most move N times. Find out the number of paths to move the ball out of grid boundary. The answer may be very large, return it after mod 10^9 + 7

.

Example 1:

Input: m = 2, n = 2, N = 2, i = 0, j = 0
Output: 6
Explanation:

此處輸入圖片的描述

Example 2:

Input: m = 1, n = 3, N = 3, i = 0, j = 1
Output: 12
Explanation:

此處輸入圖片的描述

Note:

  1. Once you move the ball out of boundary, you cannot move it back.
  2. The length and height of the grid is in range [1,50].
  3. N is in range [0,50].

題目大意

每次可以把足球從一個格子移動到另一個格子,要求最多通過N步能使得球移動到外邊的方案數?

解題方法

動態規劃

這個題有個很明顯的對於動態規劃的提示,那就是要模10^9 + 7,也就是說結果會很大,普通的搜尋可能hold不住。這個dp其實屬於對狀態的搜尋,如果看了《計算機考研機試指南》或者《挑戰程式設計競賽》的話,會很清楚的知道其實這是個搜尋的題目。

使用三維陣列dp[k][x][y]表示在不超過k步的情況下,從x,y點移動到外邊需要的步數。那麼,當前位置通過k步移動到外邊的步數等於其周圍4個位置走k - 1步移動到外邊的步數和。

因為當x,y處於邊界的時候,實際上只有兩個或者三個相鄰的位置,因為向邊界方向走的話,只需要1步就可以移動到外部。所以,如果向當前位置的周圍位置出界的話,那麼從這個方向需要出去移動步數就是1.

最後求和取模。

時間複雜度是O(N^2),空間複雜度是O(100*100).

class Solution(object):
    def findPaths(self, m, n, N, i, j):
        """
        :type m: int
        :type n: int
        :type N: int
        :type i: int
        :type j: int
        :rtype: int
        """
        dp = [[[0] * n for _ in range(m)] for _ in range(N + 1)]
        for s in range(1, N + 1):
            for x in range(m):
                for y in range(n):
                    v1 = 1 if x == 0 else dp[s - 1][x - 1][y]
                    v2 = 1 if x == m - 1 else dp[s - 1][x + 1][y]
                    v3 = 1 if y == 0 else dp[s - 1][x][y - 1]
                    v4 = 1 if y == n - 1 else dp[s - 1][x][y + 1]
                    dp[s][x][y] = (v1 + v2 + v3 + v4) % (10**9 + 7)
        return dp[N][i][j]

相似題目

參考資料

日期

2018 年 10 月 27 日 —— 10月份最後一個週末