A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
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.
Note: m and n will be at most 100.
Example 1:
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
题意
和62题类似,机器人从左上角走到右下角,每次只能向右或向下,一共有多少种不同的走法,不同的是在方格中设有障碍,障碍不能到达。
思路
先遍历第一列和第一行,如果有障碍则dp=0,否则dp=1。
其余格子如果是障碍则dp=0,否则使用62题中的方法。
代码
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
if obstacleGrid[i][0] == 1:
dp[i][0] = 0
break
else:
dp[i][0] = 1
for i in range(n):
if obstacleGrid[0][i] == 1:
dp[0][i] = 0
break
else:
dp[0][i] = 1
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1] if obstacleGrid[i][j] == 0 else 0
print(dp)
return dp[m - 1][n - 1]
网友评论