Unique Paths III
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Backtracking.
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++Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.