Unique Paths III — LeetCode 980 Python Solution

HardBit ManipulationArrayBacktrackingMatrix
Problem
#980
Reading time
4 min

The problem

You are given an m x n integer array grid where grid[i][j] could be: 1 representing the starting square. There is exactly one starting square.

Example

Input
grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output
2
Explanation
We have the following two paths:

Python solution

Python
class Solution:
    def uniquePathsIII(self, grid: List[List[int]]) -> int:
        def dfs(i: int, j: int, k: int) -> int:
            if grid[i][j] == 2:
                return int(k == cnt + 1)
            ans = 0
            for a, b in pairwise(dirs):
                x, y = i + a, j + b
                if 0 <= x < m and 0 <= y < n and (x, y) not in vis and grid[x][y] != -1:
                    vis.add((x, y))
                    ans += dfs(x, y, k + 1)
                    vis.remove((x, y))
            return ans

        m, n = len(grid), len(grid[0])
        start = next((i, j) for i in range(m) for j in range(n) if grid[i][j] == 1)
        dirs = (-1, 0, 1, 0, -1)
        cnt = sum(row.count(0) for row in grid)
        vis = {start}
        return dfs(*start, 0)

Complexity

MeasureComplexity
TimeO(3^{m \times n})
SpaceO(m \times n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 980. Unique Paths III is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 980. Unique Paths III?
LeetCode 980. Unique Paths III is rated Hard on LeetCode.
What is the time complexity of LeetCode 980. Unique Paths III?
The Python solution on this page runs in O(3^{m \times n}).
What is the space complexity of LeetCode 980. Unique Paths III?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 980. Unique Paths III cover?
LeetCode 980. Unique Paths III is tagged Bit Manipulation, Array, Backtracking 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