您的位置:首页 > 编程语言 > Python开发

leetcode 【 Unique Paths II 】 python 实现

2015-01-26 16:12 323 查看
题目

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

class Solution:
# @param obstacleGrid, a list of lists of integers
# @return an integer
def uniquePathsWithObstacles(self, obstacleGrid):
# ROW & COL
ROW = len(obstacleGrid)
COL = len(obstacleGrid[0])
# one row case
if ROW==1:
for i in range(COL):
if obstacleGrid[0][i]==1:
return 0
return 1
# one column case
if COL==1:
for i in range(ROW):
if obstacleGrid[i][0]==1:
return 0
return 1
# visit normal case
dp = [[0 for i in range(COL)] for i in range(ROW)]
for i in range(COL):
if obstacleGrid[0][i]!=1:
dp[0][i]=1
else:
break
for i in range(ROW):
if obstacleGrid[i][0]!=1:
dp[i][0]=1
else:
break
# iterator the other nodes
for row in range(1,ROW):
for col in range(1,COL):
if obstacleGrid[row][col]==1:
dp[row][col]=0
else:
dp[row][col]=dp[row-1][col]+dp[row][col-1]

return dp[ROW-1][COL-1]


思路

思路模仿Unique Path这道题:

/article/5261261.html

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

个人感觉40行的python脚本不够简洁,总是把special case等单独拎出来。后面再练习代码的时候,考虑如何让代码更简洁。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: