Unique Paths III - Problem

You are given an m x n integer array grid where grid[i][j] could be:

  • 1 representing the starting square. There is exactly one starting square.
  • 2 representing the ending square. There is exactly one ending square.
  • 0 representing empty squares we can walk over.
  • -1 representing 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.

Input & Output

Example 1 — Basic 3x3 Grid
$ Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output: 2
💡 Note: We have 7 walkable squares (including start and end). Two valid paths exist: 1→0→0→0→0→0→2 going around the obstacle in different ways.
Example 2 — Small Grid with Obstacle
$ Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
Output: 4
💡 Note: All 8 squares are walkable. Multiple paths exist from start (1) to end (2) visiting all squares exactly once.
Example 3 — No Valid Path
$ Input: grid = [[0,1],[2,0]]
Output: 0
💡 Note: Start at (0,1) with value 1, end at (1,0) with value 2. Only 4 squares total, but impossible to visit all and reach end due to grid layout.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 20
  • 1 and 2 appear exactly once in grid

Visualization

Tap to expand
Unique Paths III: Visit Every Square Exactly Once10000000002-1Goal: Visit all 11 walkable squaresStart (1) → All zeros (0) → End (2)Avoid obstacle (-1)Start: (0,0)End: (2,2)Obstacle: (2,3)Answer: 2 different valid complete paths existOrange path and Purple path both visit every walkable square exactly once
Understanding the Visualization
1
Input Grid
Grid with start (1), end (2), walkable (0), and obstacles (-1)
2
Path Exploration
Use backtracking to try all possible paths
3
Count Valid Paths
Count paths that visit all walkable squares and reach the end
Key Takeaway
🎯 Key Insight: Use backtracking to systematically try all paths while tracking visited squares
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
85.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen