Unique Paths III
Explanation & Solution
Description
You are given an m x n integer array grid where:
1represents the starting square. There is exactly one starting square.2represents the ending square. There is exactly one ending square.0represents empty squares we can walk over.-1represents obstacles that we cannot walk over.
Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.
Examples
Example 1
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output: 2
Explanation: There are two paths that visit every non-obstacle cell exactly once: right→right→right→down→down and right→right→down→down→right (adapting direction as needed).
Example 2
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
Output: 4
Explanation: There are four valid Hamiltonian paths from the start to the end covering all empty cells.
Example 3
Input: grid = [[0,1],[2,0]]
Output: 0
Explanation: No path from start to end can visit all 4 non-obstacle cells exactly once.
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 201 <= m * n <= 20-1 <= grid[i][j] <= 2- There is exactly one
1and one2in grid
Approach
Backtracking pattern
1. Count Non-Obstacle Cells
- Scan the grid to find the starting position and count all cells that are not obstacles (
!= -1) - This count tells us how many cells a valid path must visit
2. DFS with Remaining Counter
- Start DFS from the starting cell with
remaining = empty(total non-obstacle cells) - At each step, decrement
remainingto track how many cells still need to be visited
3. Check the Ending Condition
- When we reach the ending cell (
grid[r][c] === 2), check ifremaining === 1(only the end cell is left to count) - If so, this is a valid Hamiltonian path — increment
result
4. Backtrack on the Grid
- Save the cell's value, mark it as an obstacle (
-1) to prevent revisiting - Explore all four directions
- Restore the cell's original value after exploration
Key Insight
- This is a Hamiltonian path problem — NP-hard in general, but feasible here because the grid is small (≤ 20 cells). Backtracking with in-place marking is the natural approach.
Visualization
Press play to start backtracking search