MediumNo. 0576

Out of Boundary Paths — LeetCode 576 Python Solution

Topics
Dynamic Programming
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

PythonSolution
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

Time
O(m × n × k)
Space · auxiliary
O(m × n × k)

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

Related problems
No.ProblemDifficulty
0583Delete Operation for Two StringsMedium
0010Regular Expression MatchingHard
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard
0044Wildcard MatchingHard
0045Jump Game IIMedium

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 × n × k).

What is the space complexity of LeetCode 576. Out of Boundary Paths?

The Python solution on this page uses O(m × n × 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.

Free to download. Check it runs on your machine, then pick a plan.