[LeetCode] 63. Unique Paths II_ Medium tag: Dynamic Programming

时间:2021-05-15 14:32:37

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?

[LeetCode] 63. Unique Paths II_ Medium tag: Dynamic Programming

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 这个题目思路还是跟[LeetCode] 62. Unique Paths_ Medium tag: Dynamic Programming 类似,只不过在初始化和计算时要考虑是否为obstacle即可。 Code
class Solution:
def uniquePath(self, nums):
if not nums or len(nums[0]) == 0:
return 0
lr, lc = len(nums), len(nums[0])
mem = [[0] * lc for _ in range(lr)]
for i in range(lr):
if nums[i][0] != 1:
mem[i][0] = 1
else:
break
for i in range(lc):
if nums[0][i] != 1:
mem[0][i] = 1
else:
break
for i in range(1, lr):
for j in range(1, lc):
mem[i][j] = 0 if nums[i][j] == 1 else mem[i - 1][j] + mem[i][j - 1]
return mem[lr - 1][lc - 1]