63. Unique Paths II
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 3 × 3 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.
Solution: DP
class Solution(object):
def uniquePathsWithObstacles(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rows = len(grid)
cols = len(grid[0])
paths = [0] * cols
paths[0] = 1
for row in xrange(rows):
if grid[row][0]:
paths[0] = 0
for col in xrange(1, cols):
if grid[row][col]:
paths[col] = 0
else:
paths[col] += paths[col - 1]
return paths[-1]