一個機器人位於一個 m x n 網格的左上角 (起始點在下圖中標記爲“Start” )。
機器人每次只能向下或者向右移動一步。機器人試圖達到網格的右下角(在下圖中標記爲“Finish”)。
現在考慮網格中有障礙物。那麼從左上角到右下角將會有多少條不同的路徑?
網格中的障礙物和空位置分別用 1 和 0 來表示。
說明:m 和 n 的值均不超過 100。
示例 1:
輸入: [ [0,0,0], [0,1,0], [0,0,0] ] 輸出: 2 解釋: 3x3 網格的正中間有一個障礙物。
從左上角到右下角一共有 2 條不同的路徑:
- 向右 -> 向右 -> 向下 -> 向下
- 向下 -> 向下 -> 向右 -> 向右
有很多的邊界條件,考慮進去之後和62沒有區別的
基本方程:
不是障礙物時,step[i][j] = step[i-1][j] + step[i][j-1]
是障礙物時,step[i][j] = 0
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if not obstacleGrid: return 0
if obstacleGrid[len(obstacleGrid)-1][len(obstacleGrid[0])-1]: return 0 #如果右下角是個障礙物那麼就不能到達,返回0
if len(obstacleGrid) == len(obstacleGrid[0]) == 1: return 1 #只有起始點(這裏題目好像默認起始點不會是障礙點的)
#初始矩陣的構建,非常重要,這裏全部要按零初始化,第一行或者第一列出現障礙物後,後面的值要全部都是0
step = [[0 for i in range(len(obstacleGrid[0]))] for j in range(len(obstacleGrid))]
for i in range(len(obstacleGrid[0])):
if not obstacleGrid[0][i]:
step[0][i] = 1
else:
if len(obstacleGrid) == 1: return 0 #如果是單行,出現障礙物,不能到達
break
for i in range(len(obstacleGrid)):
if not obstacleGrid[i][0]:
step[i][0] = 1
else:
if len(obstacleGrid[0]) == 1: return 0
break
#標準動規
for i in range(1, len(obstacleGrid)):
for j in range(1, len(obstacleGrid[0])):
step[i][j] = step[i-1][j] + step[i][j-1] if not obstacleGrid[i][j] else 0
return step[len(obstacleGrid)-1][len(obstacleGrid[0])-1]