Unique Paths II — LeetCode 63 Python Solution

MediumArrayDynamic ProgrammingMatrix
Problem
#63
Reading time
2 min

The problem

You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]).

Example

Input
obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output
2
Explanation
There is one obstacle in the middle of the 3x3 grid above.

Python solution

Python
class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        @cache
        def dfs(i: int, j: int) -> int:
            if i >= m or j >= n or obstacleGrid[i][j]:
                return 0
            if i == m - 1 and j == n - 1:
                return 1
            return dfs(i + 1, j) + dfs(i, j + 1)

        m, n = len(obstacleGrid), len(obstacleGrid[0])
        return dfs(0, 0)

Complexity

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

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 63. Unique Paths II is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 63. Unique Paths II?
LeetCode 63. Unique Paths II is rated Medium on LeetCode.
What is the time complexity of LeetCode 63. Unique Paths II?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 63. Unique Paths II?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 63. Unique Paths II cover?
LeetCode 63. Unique Paths II is tagged Array, Dynamic Programming and Matrix 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