576. Out of Boundary Paths

Medium (Trung bình) Python 🔗 Xem trên LeetCode

📋 Đề Bài

There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.

Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.

 

Example 1:

Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
Output: 6

Example 2:

Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
Output: 12

 

Constraints:

  • 1 <= m, n <= 50
  • 0 <= maxMove <= 50
  • 0 <= startRow < m
  • 0 <= startColumn < n

🧠 Thuật Toán & Kỹ Thuật

Dynamic Programming (Quy hoạch động)DFS (Tìm kiếm theo chiều sâu)
⏱️ Thời gian O(n)
💾 Không gian O(n)

💻 Lời Giải

Python 0576-out-of-boundary-paths.py
class Solution:
    def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
        DIR = [[-1, 0], [0, -1], [0, 1], [1, 0]]
        MOD = 10**9 + 7
        
        @lru_cache(None)
        def dfs(i, j, move):
            if not (0 <= i < m and 0 <= j < n):
                return 1
            
            ans = 0
            for di, dj in DIR:
                ni = i + di
                nj = j + dj
                if move > 0:
                    ans = (ans + dfs(ni, nj, move - 1)) % MOD
                
            return ans
        
        return dfs(startRow, startColumn, maxMove)