机器人位于m x n网格的左上角。
机器人只能在任何时间点上下移动。机器人试图到达网格的右下角。
如果在网格上添加了一些障碍。会有多少条独特的路径?
障碍物和空白区域在网格中分别标记为1和0。
class Solution:
"""
@param obstacleGrid: A list of lists of integers
@return: An integer
"""
def uniquePathsWithObstacles(self, obstacleGrid):
# write your code here
if not obstacleGrid:
return 0
m = len(obstacleGrid)
n = len(obstacleGrid[0])
li = [[0] * n] * m
for i in range(m):
for j in range(n):
if obstacleGrid[i][j] == 1:
li[i][j] = 0 ######## why do I have to add this line ???########
continue
elif i == 0 and j == 0:
li[i][j] = 1
elif i == 0:
li[i][j] = li[i][j - 1]
elif j == 0:
li[i][j] = li[i - 1][j]
else:
li[i][j] = li[i - 1][j] + li[i][j - 1]
return li[m - 1][n - 1]
问题在编码中。我已经设置了用零填充的m * n矩阵。为什么我还要再将零分配给该位置呢???如果我删除那条线,似乎就行不通了。谁能告诉我为什么的原因???谢谢!
答案 0 :(得分:1)
问题是这一行:
li = [[0] * n] * m
语法[a] * n
创建浅拷贝,而不是a
的深拷贝。
示例:
n = m = 2
li[0][0] = 3
print(li) # prints [[3, 0], [3, 0]]
Link to question,并讨论了可能的解决方案。