一个机器人位于一个m*n的网格的左上角。
它每次只能向下或向右移动一格。它试图到达网格的右下角。
网格中有一些障碍物,机器人不能通过。
求有多少种不重复的路径?
备注:
1、m 和 n 都不大于 100.
2、障碍物和空地分别被标为 1 和 0。
示例:
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
思路
本题与 Leetcode算法——62、不重复路径(unique paths) 很相似,不同之处在于本题多了障碍物,因此不能通过使用数学法转换为纯粹的排列组合问题。
可以使用动态规划法。
设左上角座标为(0,0),右下角座标为(m,n)。记走到 (i,j) 的路径数为 dp(i,j),则:
1、如果 (i,j) 位置是障碍物,则 dp(i,j) = 0。
2、如果 (i,j) 位置不是障碍物,则 dp(i,j) = dp(i-1,j) + dp(i,j-1)。
python实现
def uniquePathsWithObstacles(obstacleGrid):
""" :type obstacleGrid: List[List[int]] :rtype: int """
if not obstacleGrid or obstacleGrid[0][0] == 1:
return 0
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = 1 # 起始点,一种路径
for i in range(0, m):
for j in range(0, n):
if obstacleGrid[i][j] == 0: # 当前位置没有障碍物
if i > 0:
dp[i][j] += dp[i-1][j]
if j > 0:
dp[i][j] += dp[i][j-1]
return dp[-1][-1]
if '__main__' == __name__:
obstacleGrid = [
[0,0,0],
[0,1,0],
[0,0,0]
]
print(uniquePathsWithObstacles(obstacleGrid))