Sunday, May 11, 2014

Leetcode (Python): 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 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.

Solution:

Using dynamic programming:

class Solution:
    # @param obstacleGrid, a list of lists of integers
    # @return an integer
    def uniquePathsWithObstacles(self, obstacleGrid):
        uniquePaths = [[]]
        uniquePaths[0].append(1 if obstacleGrid[0][0] == 0 else 0)
        for i in range(0,len(obstacleGrid)):
            uniquePaths.append([])
            for j in range(0, len(obstacleGrid[0])):
                uniquePaths[i].append(0)
                if obstacleGrid[i][j] == 0:
                    uniquePaths[i][j] += uniquePaths[i-1][j] if i>0 else 0
                    uniquePaths[i][j] += uniquePaths[i][j-1] if j>0 else 0
        return uniquePaths[len(obstacleGrid)-1][len(obstacleGrid[0])-1]

No comments :

Post a Comment