Out of Boundary Paths — LeetCode 576 Python Solution

MediumDynamic Programming
Problem
#576
Reading time
3 min

The problem

There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn].

Example

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

Python solution

Python
class Solution:
    def findPaths(
        self, m: int, n: int, maxMove: int, startRow: int, startColumn: int
    ) -> int:
        @cache
        def dfs(i: int, j: int, k: int) -> int:
            if not 0 <= i < m or not 0 <= j < n:
                return int(k >= 0)
            if k <= 0:
                return 0
            ans = 0
            for a, b in pairwise(dirs):
                x, y = i + a, j + b
                ans = (ans + dfs(x, y, k - 1)) % mod
            return ans

        mod = 10**9 + 7
        dirs = (-1, 0, 1, 0, -1)
        return dfs(startRow, startColumn, maxMove)

Complexity

MeasureComplexity
TimeO(m \times n \times k)
SpaceO(m \times n \times k) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 576. Out of Boundary Paths is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 576. Out of Boundary Paths?
LeetCode 576. Out of Boundary Paths is rated Medium on LeetCode.
What is the time complexity of LeetCode 576. Out of Boundary Paths?
The Python solution on this page runs in O(m \times n \times k).
What is the space complexity of LeetCode 576. Out of Boundary Paths?
The Python solution on this page uses O(m \times n \times k) auxiliary space.
What topics does LeetCode 576. Out of Boundary Paths cover?
LeetCode 576. Out of Boundary Paths is tagged Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview