Unique Paths III (LeetCode 980): Solution and Explanation
Count the 4-directional walks from the start square to the end square that step on every non-obstacle square exactly once.
Intuition
Unlike Unique Paths I and II, the walk may move in all four directions and must cover every free square. That breaks dynamic programming: whether a move is legal depends on everything visited so far.
The grid has at most 20 cells, though, so trying every self-avoiding walk is affordable. This is a classic backtracking search: step, recurse, then undo the step.
To know whether a walk covered everything, count up front how many squares must be visited (every 0 plus the start) and pass the remaining count down. When the walk lands on the 2, it counts only if that number has reached zero.
Approach: Backtracking DFS with a remaining-squares counter
- Scan the grid once to find the start and set
emptyto the number of 0 cells plus one for the start. dfs(r, c, remain)returns 0 if the cell is off the grid, an obstacle or already visited.- If the cell is the 2, return 1 when
remain == 0, otherwise 0. - Otherwise mark the cell as visited, add up
dfson the four neighbours withremain - 1, restore the cell and return the sum. - The answer is
dfs(start, empty).
Step-by-step example
grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
- There are 9 zeros, so
empty = 10: the walk must touch 10 squares (the zeros and the start) before stepping onto the 2. - The DFS tries down first. Going down the left column and right along the bottom row reaches the 2 at (2,2) with squares still unvisited, so that branch returns 0 and the search backs up.
- Down the left column to (2,0), right to (2,1), up through (1,1) to (0,1), across the top to (0,3), down to (1,3), left to (1,2) and down onto the 2 covers all 10 squares: the first walk.
- Across the top row to (0,3), down to (1,3), back along the middle row to (1,0), down to (2,0) and right along the bottom onto the 2 is the second walk.
- Every other branch either hits the 2 early or gets stuck in a corner. The answer is 2.
Code: Python, Java, C++
1class Solution:
2 def uniquePathsIII(self, grid: List[List[int]]) -> int:
3 rows, cols = len(grid), len(grid[0])
4 empty = 1
5 for r in range(rows):
6 for c in range(cols):
7 if grid[r][c] == 1:
8 sr, sc = r, c
9 elif grid[r][c] == 0:
10 empty += 1
11
12 def dfs(r: int, c: int, remain: int) -> int:
13 if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == -1:
14 return 0
15 if grid[r][c] == 2:
16 return 1 if remain == 0 else 0
17 grid[r][c] = -1
18 paths = (dfs(r + 1, c, remain - 1) + dfs(r - 1, c, remain - 1)
19 + dfs(r, c + 1, remain - 1) + dfs(r, c - 1, remain - 1))
20 grid[r][c] = 0
21 return paths
22
23 return dfs(sr, sc, empty)1class Solution {
2 private int rows, cols;
3
4 public int uniquePathsIII(int[][] grid) {
5 rows = grid.length;
6 cols = grid[0].length;
7 int empty = 1, sr = 0, sc = 0;
8 for (int r = 0; r < rows; r++) {
9 for (int c = 0; c < cols; c++) {
10 if (grid[r][c] == 1) {
11 sr = r;
12 sc = c;
13 } else if (grid[r][c] == 0) {
14 empty++;
15 }
16 }
17 }
18 return dfs(grid, sr, sc, empty);
19 }
20
21 private int dfs(int[][] grid, int r, int c, int remain) {
22 if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] == -1) {
23 return 0;
24 }
25 if (grid[r][c] == 2) {
26 return remain == 0 ? 1 : 0;
27 }
28 grid[r][c] = -1;
29 int paths = dfs(grid, r + 1, c, remain - 1) + dfs(grid, r - 1, c, remain - 1)
30 + dfs(grid, r, c + 1, remain - 1) + dfs(grid, r, c - 1, remain - 1);
31 grid[r][c] = 0;
32 return paths;
33 }
34}1class Solution {
2public:
3 int uniquePathsIII(vector<vector<int>>& grid) {
4 rows = grid.size();
5 cols = grid[0].size();
6 int empty = 1, sr = 0, sc = 0;
7 for (int r = 0; r < rows; r++) {
8 for (int c = 0; c < cols; c++) {
9 if (grid[r][c] == 1) {
10 sr = r;
11 sc = c;
12 } else if (grid[r][c] == 0) {
13 empty++;
14 }
15 }
16 }
17 return dfs(grid, sr, sc, empty);
18 }
19
20private:
21 int rows = 0, cols = 0;
22
23 int dfs(vector<vector<int>>& grid, int r, int c, int remain) {
24 if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] == -1) {
25 return 0;
26 }
27 if (grid[r][c] == 2) {
28 return remain == 0 ? 1 : 0;
29 }
30 grid[r][c] = -1;
31 int paths = dfs(grid, r + 1, c, remain - 1) + dfs(grid, r - 1, c, remain - 1)
32 + dfs(grid, r, c + 1, remain - 1) + dfs(grid, r, c - 1, remain - 1);
33 grid[r][c] = 0;
34 return paths;
35 }
36};Time and space complexity
O(3^k)
k is the number of free squares. After the first step each cell has at most three unvisited directions, so the search tree has at most about 3^k leaves. With k <= 20 and heavy pruning by visited cells, this runs fast.
O(k)
The recursion is as deep as the longest walk, which is at most the number of free squares. The grid itself is used for the visited marks.
Other approaches
DP over subsets (Hamiltonian path DP) (time O(2^k * k), space O(2^k * k))
Let dp[mask][cell] be the number of walks that visit exactly the cells in mask and end at cell. Transitions add a neighbouring cell to the mask. It is polynomial in the number of masks but uses far more memory than the DFS.
DFS with a visited bitmask (time O(3^k), space O(k))
Same search, but keep visited cells in an integer bitmask instead of writing -1 into the grid. Useful when the input must not be modified.
Common mistakes
- Forgetting to count the start square. The walk visits the start too, so
emptybegins at 1, not 0. - Counting a walk the moment it touches the 2. It only counts when every free square was already visited.
- Not restoring the cell after the recursive calls. Without the undo, later branches see stale visited marks and miss walks.
- Trying to use the Unique Paths I or II DP table. Moves go in four directions and must cover every square, so the table recurrence does not apply.
Frequently asked questions
Why is backtracking fast enough here?
The grid has at most 20 cells. Visited squares and obstacles cut most branches immediately, so the number of explored walks stays small in practice.
Why mark visited cells with -1?
Reusing the obstacle value means one check rejects both obstacles and squares already on the walk. The cell is set back to 0 when the call returns.
Can the answer be zero even when a path exists from start to end?
Yes. A path that reaches the 2 but skips any free square does not count. Example 3 has a direct path, but none of them covers all four squares.
Is there a quick check for impossible grids?
Colour the grid like a chessboard. Each step changes colour, so the walk length fixes whether the start and end must share a colour. If the colours do not match, the answer is 0. The DFS finds this anyway, so the check is optional.