[LeetCode]题解(python):063-Unique path II


题目来源


https://leetcode.com/problems/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.


题意分析


Input:a matrix as list[list[int]]

Output:the number of path

Conditions:从左上角走到左下角,注意有障碍不能通过


题目思路


上一题是用数学方法直接解,这一题用动态规划吧,因为每一步都会基于上一格或者是左一格,动态方程为dp[i][j] = dp[i][j-1] + dp[i-1][j]

注意初始化的时候如果遇到障碍,后面的位置不能初始化为0了


AC代码(Python)


 1 class Solution(object):
 2     def uniquePathsWithObstacles(self, obstacleGrid):
 3         """
 4         :type obstacleGrid: List[List[int]]
 5         :rtype: int
 6         """
 7         m = len(obstacleGrid)
 8         n = len(obstacleGrid[0])
 9         dp = [[0 for i in range(n)] for j in range(m)]
10         for i in range(n):
11             if obstacleGrid[0][i] == 1:
12                 break
13             else:
14                 dp[0][i] = 1
15         
16         for i in range(m):
17             if obstacleGrid[i][0] == 1:
18                 break
19             else:
20                 dp[i][0] = 1
21         
22         for i in range(1, m):
23             for j in range(1, n):
24                 if obstacleGrid[i][j] == 0:
25                     dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
26         
27         return dp[m - 1][n - 1]

 

posted @ 2016-01-01 17:44  loadofleaf  Views(378)  Comments(0Edit  收藏  举报