leetcode 【 Unique Paths II 】 python 实现

题目

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.

 

代码:oj测试通过 Runtime: 48 ms

 1 class Solution:
 2     # @param obstacleGrid, a list of lists of integers
 3     # @return an integer
 4     def uniquePathsWithObstacles(self, obstacleGrid):
 5         # ROW & COL
 6         ROW = len(obstacleGrid)
 7         COL = len(obstacleGrid[0])
 8         # one row case
 9         if ROW==1:
10             for i in range(COL):
11                 if obstacleGrid[0][i]==1:
12                     return 0
13             return 1
14         # one column case
15         if COL==1:
16             for i in range(ROW):
17                 if obstacleGrid[i][0]==1:
18                     return 0
19             return 1
20         # visit normal case
21         dp = [[0 for i in range(COL)] for i in range(ROW)]
22         for i in range(COL):
23             if obstacleGrid[0][i]!=1:
24                 dp[0][i]=1
25             else:
26                 break
27         for i in range(ROW):
28             if obstacleGrid[i][0]!=1:
29                 dp[i][0]=1
30             else:
31                 break
32         # iterator the other nodes
33         for row in range(1,ROW):
34             for col in range(1,COL):
35                 if obstacleGrid[row][col]==1:
36                     dp[row][col]=0
37                 else:
38                     dp[row][col]=dp[row-1][col]+dp[row][col-1]
39         
40         return dp[ROW-1][COL-1]

思路

思路模仿Unique Path这道题:

http://www.cnblogs.com/xbf9xbf/p/4250359.html

只不过多了某些障碍点;针对障碍点,加一个判断条件即可:如果遇上障碍点,那么到途径这个障碍点到达终点的可能路径数为0。然后继续迭代到尾部即可。

个人感觉40行的python脚本不够简洁,总是把special case等单独拎出来。后面再练习代码的时候,考虑如何让代码更简洁。

转载于:https://www.cnblogs.com/xbf9xbf/p/4250611.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值