#980
Unique Paths III
HardArrayBacktrackingBit ManipulationMatrixBacktrackingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(4^(m*n)) | O(4^(m*n)) |
| Space | O(m*n) | O(m*n) |
💡
Intuition
Time O(4^(m*n))Space O(m*n)
The optimal solution uses backtracking with pruning to efficiently explore paths. By keeping track of the number of empty squares to visit and marking squares as visited, we can avoid unnecessary paths and reduce the search space significantly.
⚙️
Algorithm
3 steps- 1Step 1: Count the number of empty squares and identify the starting and ending positions.
- 2Step 2: Implement a backtracking function that explores all four directions recursively.
- 3Step 3: Use a visited set to track which squares have been visited and ensure all empty squares are covered before reaching the end.
solution.py20 lines
1def uniquePathsIII(grid):
2 m, n = len(grid), len(grid[0])
3 start_x = start_y = empty_count = 0
4 for i in range(m):
5 for j in range(n):
6 if grid[i][j] == 1:
7 start_x, start_y = i, j
8 if grid[i][j] == 0:
9 empty_count += 1
10 def backtrack(x, y, visited):
11 if (x < 0 or x >= m or y < 0 or y >= n or grid[x][y] == -1 or visited[x][y]):
12 return 0
13 if grid[x][y] == 2:
14 return 1 if visited.sum() == empty_count + 1 else 0
15 visited[x][y] = True
16 paths = backtrack(x + 1, y, visited) + backtrack(x - 1, y, visited) + backtrack(x, y + 1, visited) + backtrack(x, y - 1, visited)
17 visited[x][y] = False
18 return paths
19 visited = [[False] * n for _ in range(m)]
20 return backtrack(start_x, start_y, visited)ℹ
Complexity note: The time complexity remains exponential due to the recursive nature of the backtracking, but the use of pruning (marking visited) helps reduce the number of paths explored. The space complexity is O(m*n) due to the recursion stack and visited grid.
- 1Understanding the grid structure is crucial for pathfinding.
- 2Backtracking is a powerful technique for exploring all possible solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.