Unique Paths II

  • tags: [DP_Matrix]

Question

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.
Note
m and n will be at most 100.

Example
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.

题解

在上题的基础上加了obstacal这么一个限制条件,那么也就意味着凡是遇到障碍点,其路径数马上变为0,需要注意的是初始化环节和上题有较大不同。

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

sol=Solution()
obstacleGrid=[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
sol.uniquePathsWithObstacles(obstacleGrid)
class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        m,n = len(obstacleGrid),len(obstacleGrid[0])
        ans = [[0 for i in range(n)] for j in range(m)]
        ans[0][0] = 1
        for i in range(m):
            for j in range(n):
                if obstacleGrid[i][j] == 1:
                    ans[i][j] = 0
                elif i != 0 and j == 0:
                    ans[i][j] = ans[i - 1][j]
                elif i == 0 and j != 0:
                    ans[i][j] = ans[i][j - 1]
                elif i != 0 and j != 0:
                    ans[i][j] = ans[i -1][j] + ans[i][j - 1]
        return ans[m - 1][n - 1]
sol=Solution()
obstacleGrid=[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
sol.uniquePathsWithObstacles(obstacleGrid)

results matching ""

    No results matching ""