Problem 980

Abstract / Summary

Find the number of ways to move from the start to the finish visiting every empty cell once in a grid with obstacles.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0980.py

class Solution:
    def uniquePathsIII(self, grid: List[List[int]]) -> int:
        width  = len(grid[0])
        height = len(grid)

        result = 0

        def id(x, y):
            return 1 << (x + width * y)

        initmask = 0
        finish   = 0
        startx, starty = -1, -1
        lastx,  lasty  = -1, -1
        for y in range(height):
            for x in range(width):
                if grid[y][x] == 1:
                    initmask |= id(x, y)
                    startx = x
                    starty = y
                if grid[y][x] == 2:
                    lastx = x
                    lasty = y
                if grid[y][x] != -1:
                    finish |= id(x, y)

        def deeper(x, y, have):
            if x == lastx and y == lasty:
                if have == finish:
                    nonlocal result
                    result += 1
                return
            
            if x < 0 or y < 0 or x >= width or y >= height:
                return

            if x > 0          and not (id(x-1, y) & have):
                deeper(x-1, y, have | id(x-1, y))
            if x < width - 1  and not (id(x+1, y) & have):
                deeper(x+1, y, have | id(x+1, y))
            if y > 0          and not (id(x, y-1) & have):
                deeper(x, y-1, have | id(x, y-1))
            if y < height - 1 and not (id(x, y+1) & have):
                deeper(x, y+1, have | id(x, y+1))
        
        deeper(startx, starty, initmask)
        return result
47 lines | 1552 bytes | submitted September 22, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 83% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Bit Manipulation
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the “Unique Paths III” problem by enumerating every possible walk that starts on the cell marked 1, ends on the cell marked 2, and visits every non-obstacle cell exactly once. The core strategy is a depth-first search (DFS) that carries a compact bitmask representing the set of cells already visited. When the search reaches the destination, it verifies that the visited mask matches the mask of all traversable cells; if so, a valid path is counted.

Initialization and Mask Construction

The algorithm begins by extracting the grid dimensions and preparing a mutable result counter.

width  = len(grid[0])
height = len(grid)
result = 0

A helper id function maps a coordinate (x, y) to a distinct bit position inside a 64-bit integer. The shift amount is computed as x + width * y, guaranteeing a unique power-of-two for each cell.

def id(x, y):
    return 1 << (x + width * y)

Three masks are built in a single scan of the grid:

  • initmask - the bit for the start cell (value 1).
  • finish - the union of bits for every cell that is not an obstacle (-1).
  • startx, starty - coordinates of the start cell.
  • lastx, lasty - coordinates of the end cell (2).

During the scan, when a cell equals 1 its bit is added to initmask and the start coordinates are recorded. When a cell equals 2 its coordinates are stored as the destination. Every cell that is not -1 contributes its bit to finish, ensuring that obstacles are excluded from the required visitation set.

initmask = 0
finish   = 0
startx, starty = -1, -1
lastx,  lasty  = -1, -1
for y in range(height):
    for x in range(width):
        if grid[y][x] == 1:
            initmask |= id(x, y)
            startx = x
            starty = y
        if grid[y][x] == 2:
            lastx = x
            lasty = y
        if grid[y][x] != -1:
            finish |= id(x, y)

At the end of this phase the algorithm possesses all static information required for the recursive exploration.

Depth-First Search with Bitmask State

The recursive function deeper receives the current position (x, y) and the accumulated visitation mask have.

def deeper(x, y, have):
    if x == lastx and y == lasty:
        if have == finish:
            nonlocal result
            result += 1
        return
    if x < 0 or y < 0 or x >= width or y >= height:
        return
    if x > 0          and not (id(x-1, y) & have):
        deeper(x-1, y, have | id(x-1, y))
    if x < width - 1  and not (id(x+1, y) & have):
        deeper(x+1, y, have | id(x+1, y))
    if y > 0          and not (id(x, y-1) & have):
        deeper(x, y-1, have | id(x, y-1))
    if y < height - 1 and not (id(x, y+1) & have):
        deeper(x, y+1, have | id(x, y+1))

The first conditional detects arrival at the destination cell. It then checks whether the current mask have equals the pre-computed finish mask; equality means every traversable cell has been visited, and the global result is incremented. The function returns immediately after handling the destination, preventing any further moves beyond the endpoint.

Boundary checks guard against coordinates outside the grid. The four directional moves are considered only when the target cell lies inside the grid and its bit is not already set in have. The expression not (id(nx, ny) & have) acts as a fast “not visited” test. When a move is legal, the recursion proceeds with the new position and an updated mask that includes the newly visited cell (have | id(nx, ny)).

The initial call launches the search from the start cell with the mask containing only the start bit:

deeper(startx, starty, initmask)
return result

Edge Cases Handled

The code naturally accommodates several boundary conditions:

  • Obstacles - Cells marked -1 never contribute to the finish mask, so the visitation test have == finish ignores them. Moreover, because their bits are absent from finish, the DFS never attempts to step onto them; the not (id(nx, ny) & have) guard prevents revisiting any cell, including obstacles that were never added to have.

  • Grid borders - The explicit checks x < 0, y < 0, x >= width, and y >= height stop recursion when a move would leave the grid, ensuring no index errors.

  • Single-cell grids - If the start and end cells coincide (both 1 and 2 on the same location), the initial mask already contains the only traversable bit. The first conditional in deeper sees that the current position equals the destination and that have matches finish, counting the solitary path.

  • Disconnected traversable area - When the start cannot reach the end because obstacles partition the grid, the DFS explores all reachable cells but never satisfies have == finish at the destination, resulting in a zero count without extra handling.

Performance Optimizations

The implementation leverages several techniques to keep the exhaustive search efficient:

  • Bitmask representation - Using a single integer to encode visited cells enables constant-time checks and updates (& and | operations). This avoids the overhead of mutable 2-D boolean arrays or sets for each recursive call.

  • Early termination at the destination - As soon as the search reaches the end cell, it validates the mask and returns. No further branching occurs beyond the endpoint, reducing unnecessary recursion depth.

  • Nonlocal accumulator - The result variable is captured by the nested function, allowing direct increment without returning values through the call stack. This eliminates the need to aggregate results from each recursive branch.

  • Selective expansion - The four directional calls are guarded by both boundary checks and the “not visited” test. This prevents the algorithm from generating recursive calls that would immediately fail, cutting down the total number of explored states.

  • Pre-computed masks - The finish mask is built once before recursion, so the equality test at the destination is a single integer comparison rather than a scan of the grid.

Together, these choices keep the search tight, especially for grids that fit within the 64-bit mask limit (up to 64 traversable cells). The recursion explores only valid, non-repeating paths, and the bitwise operations ensure minimal per-step overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a treasure hunt on a square grid that looks like a checkerboard. Some spots on the board have obstacles like walls that you cannot walk through, while other spots are open for you to step on. The game begins at a special starting square and ends at a target square. The goal of this puzzle is to find every possible way to walk across every single open square on the board exactly one time before finally reaching the end.

The program creates a map to remember which squares have been visited. It looks at the whole board to figure out where the walls are and marks all the empty spaces that must be visited. Think of it like coloring in squares on paper as you walk through a maze.

The code uses a special trick to explore every path. It starts at the beginning point and looks at all the directions it can move, such as left, right, up, or down. If a move goes to a square that is allowed and has not been stepped on yet, the program moves there and repeats the process.

Because the computer is very fast, it tries every single combination. If it reaches the target square and discovers that it has successfully stepped on every empty spot on the grid, it counts that as a success and marks it down. By the time it finishes checking every single turn, it will know exactly how many different ways exist to complete the puzzle.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.74 | σ = 1.60

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python Java C++ TS
WalkCCC Java C++
leetcode.ca Python Java C++ JS Go TS
LeetcodeHelp Python Java C++
Progiez Python Java C++
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq Java
halfrost Go
haoel Python
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
martianoff Scala
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq Java
halfrost Go
haoel Python
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
martianoff Scala
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
36 links | 23 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality