Problem 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.
Solutions
The solution for this problem is also pretty obvious. In the previous part, we examine dynamic solutions and combinatoric solution. However, in this problem, we are no longer able to use the combinatoric solution! Below is just a dynamic solution in python.
class Solution: # @param {integer[][]} obstacleGrid # @return {integer} def uniquePathsWithObstacles(self, obstacleGrid): m = len(obstacleGrid) n = len(obstacleGrid[0]) a = [0] * (n+1) a[-1] = 1 for i in range(1,n+1): if obstacleGrid[m-1][-i] == 0: a[n-i] = a[n-i+1] a[-1] = 0 for j in range(2, m+1): for i in range(1, n+1): if obstacleGrid[m-j][-i] == 0: a[n-i] += a[n-i + 1] else: a[n-i] = 0 return a[0]
No comments:
Post a Comment