Daily LeetCode 63. Unique Paths II

https://leetcode.com/problems/unique-paths-ii/

Medium

问题描述:

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?

img

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:

1
2
3
4
5
6
7
8
9
10
11
12
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

思路及代码:

这一题是昨天机器人走路问题的进阶版本,与Unique Paths的区别在,这一题设置了障碍方格,我们只需要在昨天的代码的基础上,对障碍方格进行处理,将障碍方格对应的dp[i][j]设置为0即可。

我还对昨天的代码进行了一部分修改,以适应单行或者单列方格的情况。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
if len(obstacleGrid) == 1 and len(obstacleGrid[0]) == 1:
if obstacleGrid[0][0] == 1:
return 0
else:
return 1
row = len(obstacleGrid) + 1
column = len(obstacleGrid[0]) + 1
dp = [[0] * column for _ in range(row)]
for i in range(row - 1, 0, -1):
for j in range(column - 1, 0, -1):
if obstacleGrid[row - 2][column - 2] == 0:
dp[row - 2][column - 2] = 1
if obstacleGrid[i - 1][j - 1] == 1:
dp[i - 1][j - 1] = 0
else:
dp[i - 1][j - 1] = dp[i][j - 1] + dp[i - 1][j]

return dp[0][0]