Out of Boundary Paths

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:
class Solution:
    def find(self, i, j, m, n, rem):
        if rem < 0:
            return 0
        if i < 0 or i >= m or j < 0 or j >= n:
            return 1
        key = (i, j, rem)
        if key in self.cache:
            return self.cache[key]
        ctr = 0
        for x, y in [(i - 1, j), (i, j + 1), (i + 1, j), (i, j - 1)]:
            ctr += self.find(x, y, m, n, rem - 1)
        self.cache[key] = ctr
        return ctr
    
    def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
        self.cache = {}
        return self.find(startRow, startColumn, m, n, maxMove) % (10 ** 9 + 7)

Comments

Popular posts from this blog

Encrypt and Decrypt Strings

Degree of an Array

Minimum Sum of Four Digit Number After Splitting Digits