1.题目描述

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

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 1:
Input:
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

2.思路分析

这道题也是一道考察动态规划算法的基础题,简单分析即可理清思路。我们把到达(i,j)位置的路径条数记为f(i, j).那么很显然有如下三条规则:

  1. 如果在(i,j)处有障碍物,那么很显然我们到达不了(i, j)这个位置,f(i, j) = 0
  2. 由于只能向右或者向下移动,那么要达到(i, j)这个位置,只有两种途径,从(i -1 ,j)位置向下移动一步,从(i, j -1)位置向右移动一步。所以到达(i, j)的路径条数应该为到达(i -1,j)和到达(i, j - 1)的路径条数之和。即f(i, j) = f(i - 1, j) + f(i, j -1)
  3. 当(0, 0)处没有障碍物时,f(0,0) = 1,当(0,0)处有障碍物时,那也去不了,f(0,0) = 0
    根据这三条规则,就可以写出代码.

3.代码实现

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid):
        """ :type obstacleGrid: List[List[int]] :rtype: int """
        if (not obstacleGrid) or (obstacleGrid[0][0] == 1):
            return 0
        row = len(obstacleGrid)
        colum = len(obstacleGrid[0])
        res = [[0 for i in range(colum)] for j in range(row)]  
        for i in range(row):
            for j in range(colum):
                if (i == 0  and j == 0):
                    res[i][j] = 1
                    continue
                if (obstacleGrid[i][j] == 1):
                    res[i][j] = 0
                else:   
                    res[i][j] = 0
                    if (i > 0):
                        res[i][j] += res[i - 1][j]
                    if (j > 0): 
                        res[i][j] += res[i][j - 1]
        return res[row -1][colum - 1]         
if __name__ == '__main__':
    grid = [
    [0,0,0],
    [0,1,0],
    [0,0,0]
    ]
    res = Solution()
    ans = res.uniquePathsWithObstacles(grid)
    print(ans)