LeetCode #63 Unique Paths II

Problem

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.

Example

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

Solution

Method: Dynamic Programming

Time Complexity: O(m * n)

Space Complexity: O(m * n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:
def initialize(self, obstacleGrid):
rows = len(obstacleGrid)
cols = len(obstacleGrid[0])
table = [[1] * cols for _ in range(rows)]

reset = False
for col in range(cols):
if obstacleGrid[0][col] == 1:
reset = True
if reset:
table[0][col] = 0

reset = False
for row in range(0, rows):
if obstacleGrid[row][0] == 1:
reset = True
if reset:
table[row][0] = 0

return rows, cols, table

def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
rows, cols, table = self.initialize(obstacleGrid)

for row in range(1, rows):
for col in range(1, cols):
if obstacleGrid[row][col] == 1:
table[row][col] = 0
else:
table[row][col] = table[row - 1][col] + table[row][col - 1]

return table[-1][-1]

or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[1]*n for _ in range(m)] # dp[i][j] stores number of paths getting [i][j]
for i in range(m):
if obstacleGrid[i][0] == 1:
for ix in range(i,m):
dp[ix][0] = 0
break;
for j in range(n):
if obstacleGrid[0][j] == 1:
for jx in range(j,n):
dp[0][jx] = 0
break;
for i in range(1,m):
for j in range(1,n):
if obstacleGrid[i][j] == 1:
dp[i][j] = 0
else:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[m-1][n-1]