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 - DFS Approach INPUT Grid (3x4): 1 START 0 0 0 0 0 0 0 0 0 2 END -1 Start (1) End (2) Empty (0) Obstacle (-1) grid = [[1,0,0,0], [0,0,0,0], [0,0,2,-1]] Empty cells to visit: 11 ALGORITHM STEPS 1 Initialize Count empty cells, find start 2 DFS from Start Explore all 4 directions 3 Track Visited Mark cells, backtrack 4 Count Valid Paths If end + all visited = OK Path Example: ... S E Visit all 11 cells before end dfs(x,y,remaining) --> explore 4 dirs, backtrack FINAL RESULT Path 1: Path 2: Output: 2 OK - Found 2 valid paths Each visits all 11 cells Key Insight: DFS with backtracking explores ALL possible paths from start to end. We mark cells visited during exploration and unmark when backtracking. A path is valid only if we reach the end after visiting ALL non-obstacle cells exactly once. Time: O(4^(m*n)), Space: O(m*n) TutorialsPoint - Unique Paths III | DFS with Backtracking
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