Unique Paths II
Question
https://leetcode.com/problems/unique-paths-ii/?tab=Description
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1
and 0
respectively in the grid.
For example, There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2
.
Note: m
and n
will be at most 100.
Tags
- array
- dynamic programming
Analysis
This problem is very similar to the previous one (Unique Paths I). Thus, we will follow almost the same algorithms: start from the right-bottom position and use the same recursive equation.
The only difference is that we need to set the value to 0 directly if the corresponding position has obstacle according to the obstacleGrid table.
Code:
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if obstacleGrid == []:
return 0
height = len(obstacleGrid)
width = len(obstacleGrid[0])
dp = [[0] * (width + 1) for _ in range(height + 1)]
for i in range(height - 1, -1, -1):
for j in range(width - 1, -1, -1):
if i == height - 1 and j == width - 1:
dp[i][j] = 1 - obstacleGrid[i][j]
continue
if obstacleGrid[i][j] == 1:
dp[i][j] = 0
else:
dp[i][j] = dp[i][j + 1] + dp[i + 1][j]
return dp[0][0]