码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-01-01 18:53:12      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:


题目来源


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]

 

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

标签:

原文地址:http://www.cnblogs.com/loadofleaf/p/5093528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!