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等单独拎出来。后面再练习代码的时候,考虑如何让代码更简洁。

posted on   承续缘  阅读(235)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示