To solve this problem, we need to determine the number of unique paths from the top-left corner to the bottom-right corner of a grid, avoiding obstacles. The allowed moves are right and down.
Approach
The problem can be efficiently solved using dynamic programming (DP) with space optimization. Here's the detailed approach:
- Edge Cases Handling: If the start or end cell is an obstacle, return 0 immediately as no path exists.
- DP Array Initialization: Use a 1D DP array where
dp[j]represents the number of ways to reach the j-th column in the current row. - First Row Setup: For the first row, each cell can only be reached from the left cell. If an obstacle is encountered, all subsequent cells in the row are unreachable.
- DP Transition: For each subsequent row:
- For the first column, check if the cell is an obstacle. If so, set
dp[0]to 0 (unreachable). - For other columns, if the cell is an obstacle, set
dp[j]to 0. Otherwise,dp[j]is the sum of the path count from the cell above (previous row'sdp[j]) and the cell to the left (current row'sdp[j-1]).
- For the first column, check if the cell is an obstacle. If so, set
Solution Code
def uniquePathsWithObstacles(obstacleGrid):
if not obstacleGrid or obstacleGrid[0][0] == 1:
return 0
m = len(obstacleGrid)
n = len(obstacleGrid[0])
if obstacleGrid[m-1][n-1] == 1:
return 0
dp = [0] * n
dp[0] = 1 # Starting cell
# Fill first row
for j in range(1, n):
if obstacleGrid[0][j] == 0:
dp[j] = dp[j-1]
else:
dp[j] = 0
# Fill remaining rows
for i in range(1, m):
# Update first column of current row
if obstacleGrid[i][0] == 1:
dp[0] = 0
# Update other columns
for j in range(1, n):
if obstacleGrid[i][j] == 1:
dp[j] = 0
else:
dp[j] += dp[j-1] # dp[j] was previous row's value, add left value
return dp[-1]
Explanation
- Edge Cases: The code first checks if the grid is empty or if the start/end cells are blocked.
- First Row: The first row is filled by checking if each cell is reachable from the left (previous cell in the row).
- Subsequent Rows: For each row, the first column is updated based on the cell above. For other columns, the value is the sum of the path count from the cell above (stored in
dp[j]) and the cell to the left (stored indp[j-1]).
This approach uses O(n) space (where n is the number of columns) instead of O(mn) space, making it efficient in terms of memory usage. The time complexity is O(mn) since each cell is processed once.
Example: For the grid [[0,0,0],[0,1,0],[0,0,0]], the output is 2, which is the correct number of unique paths avoiding the obstacle.
This solution efficiently handles all possible cases and provides an optimal way to compute the number of unique paths.

作者声明:本文包含人工智能生成内容。