Unique Paths III
Master this topic with zero to advance depth.
Unique Paths III
The Grid Coverage Problem
Find the number of paths from the starting square to the ending square that walk over every non-obstacle square exactly once.
Backtracking with Path Counting
- Count the total number of empty squares ().
- DFS from the start, marking cells as visited (-1).
- If we reach the end and our current path length equals (including the target), we found a valid path.
Find the number of paths in a grid that visit every empty square exactly once. Includes visual grid-coverage trace.
Examples
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output: 2
Approach 1
Level I: Backtracking (DFS)
Intuition
Try all possible paths from start to end, counting steps taken.
Iterate through the grid to find the start and count empty cells. DFS in 4 directions. If we reach '2' and steps == totalEmpty, increment count.
âą O(3^{M * N})đž O(M * N)
Detailed Dry Run
Trace for 1x3: [1, 0, 2]
1. Start at (0,0), empty=2.
2. Move to (0,1), steps=1. Mark visited.
3. Move to (0,2), steps=2. Target reached! Count++Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.