Unique Paths III - Problem
π― Grid Path Explorer Challenge
Imagine you're a robot explorer navigating a mysterious grid-based terrain. Your mission is to find all possible paths from your starting position to the target destination with one crucial constraint: you must visit every accessible square exactly once!
You're given an m Γ n integer grid where each cell represents:
1- Your starting square (exactly one exists)2- The ending square (exactly one exists)0- Empty squares you can walk over-1- Obstacles that block your path
Goal: Return the number of unique 4-directional walks from start to end that visit every non-obstacle square exactly once.
Example: In a 3Γ3 grid with start at (0,0), end at (2,2), and one obstacle, you might find 4 different valid paths that cover all walkable squares.
Input & Output
example_1.py β Basic Grid
$
Input:
grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
βΊ
Output:
2
π‘ Note:
There are exactly 2 paths that visit every walkable square exactly once and end at the target. Both paths start from (0,0), visit all zeros, and end at (2,2).
example_2.py β Simple Path
$
Input:
grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
βΊ
Output:
4
π‘ Note:
With no obstacles, there are 4 different ways to traverse all squares exactly once from start to end, considering different path combinations.
example_3.py β No Valid Path
$
Input:
grid = [[0,1],[2,0]]
βΊ
Output:
0
π‘ Note:
There's no valid path because we cannot visit all walkable squares exactly once due to the grid layout constraints.
Constraints
- m == grid.length
- n == grid[i].length
- 1 β€ m, n β€ 20
- 1 β€ m Γ n β€ 20
- grid[i][j] is -1, 0, 1, or 2
- There is exactly one starting square and one ending square
Visualization
Tap to expand
Understanding the Visualization
1
Scout the Territory
Count all walkable squares and locate start/end positions
2
Begin Exploration
Start DFS from the beginning position, trying each direction
3
Mark Progress
Temporarily mark visited squares to avoid revisiting in current path
4
Check Victory
When reaching end, verify all walkable squares were visited
5
Backtrack & Continue
Unmark squares and try alternative routes to find all solutions
Key Takeaway
π― Key Insight: Backtracking with state management allows us to systematically explore all possible paths while ensuring we visit every walkable square exactly once
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code