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
Difficulty
and has an acceptance rate of about 83% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Bit Manipulation
- Matrix
AI Disclaimer
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.
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 (value1).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
-1never contribute to thefinishmask, so the visitation testhave == finishignores them. Moreover, because their bits are absent fromfinish, the DFS never attempts to step onto them; thenot (id(nx, ny) & have)guard prevents revisiting any cell, including obstacles that were never added tohave. -
Grid borders - The explicit checks
x < 0,y < 0,x >= width, andy >= heightstop recursion when a move would leave the grid, ensuring no index errors. -
Single-cell grids - If the start and end cells coincide (both
1and2on the same location), the initial mask already contains the only traversable bit. The first conditional indeepersees that the current position equals the destination and thathavematchesfinish, 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 == finishat 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
resultvariable 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
finishmask 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 212: Word Search II
Extra
- 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