576-out-of-boundary-paths

Try it on leetcode

Description

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

Solution(Python)

class Solution:
    def findPaths(
        self, m: int, n: int, maxMove: int, startRow: int, startColumn: int
    ) -> int:
        return self.topdown(m, n, maxMove, startRow, startColumn)

    # Time Complexity: O(4^n)
    # Space Complexity: O(n)
    def bruteforce(
        self, m: int, n: int, maxMove: int, startRow: int, startColumn: int
    ) -> int:
        if startRow == m or startColumn == n or startRow < 0 or startColumn < 0:
            return 1
        if maxMove == 0:
            return 0

        return (
            self.bruteforce(m, n, maxMove - 1, startRow - 1, startColumn)
            + self.bruteforce(m, n, maxMove - 1, startRow + 1, startColumn)
            + self.bruteforce(m, n, maxMove - 1, startRow, startColumn - 1)
            + self.bruteforce(m, n, maxMove - 1, startRow, startColumn + 1)
        )

    # Time Complexity: O(m*n*N)
    # Space Complexity: O(m*n*N)
    @cache
    def topdown(
        self, m: int, n: int, maxMove: int, startRow: int, startColumn: int
    ) -> int:
        if startRow == m or startColumn == n or startRow < 0 or startColumn < 0:
            return 1
        if maxMove == 0:
            return 0

        return (
            self.topdown(m, n, maxMove - 1, startRow - 1, startColumn)
            + self.topdown(m, n, maxMove - 1, startRow + 1, startColumn)
            + self.topdown(m, n, maxMove - 1, startRow, startColumn - 1)
            + self.topdown(m, n, maxMove - 1, startRow, startColumn + 1)
        ) % ((10**9) + 7)