1
+ '''
2
+ A robot is located at the top-left corner of a m x n grid
3
+ (marked 'Start' in the diagram below).
4
+
5
+ The robot can only move either down or right at any point
6
+ in time. The robot is trying to reach the bottom-right
7
+ corner of the grid (marked 'Finish' in the diagram below).
8
+
9
+ Now consider if some obstacles are added to the grids.
10
+ How many unique paths would there be?
11
+
12
+ An obstacle and space is marked as 1 and 0 respectively
13
+ in the grid.
14
+
15
+ Example:
16
+ Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
17
+ Output: 2
18
+ Explanation: There is one obstacle in the middle of the
19
+ 3x3 grid above.
20
+ There are two ways to reach the bottom-right
21
+ corner:
22
+ 1. Right -> Right -> Down -> Down
23
+ 2. Down -> Down -> Right -> Right
24
+
25
+ Example:
26
+ Input: obstacleGrid = [[0,1],[0,0]]
27
+ Output: 1
28
+
29
+ Constraints:
30
+ - m == obstacleGrid.length
31
+ - n == obstacleGrid[i].length
32
+ - 1 <= m, n <= 100
33
+ - obstacleGrid[i][j] is 0 or 1.
34
+ '''
35
+ #Difficulty: Medium
36
+ #41 / 41 test cases passed.
37
+ #Runtime: 40 ms
38
+ #Memory Usage: 14.1 MB
39
+
40
+ #Runtime: 40 ms, faster than 78.35% of Python3 online submissions for Unique Paths II.
41
+ #Memory Usage: 14.1 MB, less than 94.59% of Python3 online submissions for Unique Paths II.
42
+
43
+ class Solution :
44
+ def uniquePathsWithObstacles (self , obstacleGrid : List [List [int ]]) -> int :
45
+
46
+ # count paths in the first row
47
+ for j in range (len (obstacleGrid [0 ])):
48
+ if obstacleGrid [0 ][j ] != 1 :
49
+ if j == 0 :
50
+ obstacleGrid [0 ][j ] = 1
51
+ else :
52
+ obstacleGrid [0 ][j ] += obstacleGrid [0 ][j - 1 ]
53
+ else :
54
+ obstacleGrid [0 ][j ] = 0
55
+
56
+ # count paths in the rest of the matrix
57
+ for i in range (1 , len (obstacleGrid )):
58
+ for j in range (len (obstacleGrid [0 ])):
59
+ if obstacleGrid [i ][j ] != 1 :
60
+ if j != 0 :
61
+ obstacleGrid [i ][j ] += (obstacleGrid [i ][j - 1 ] + obstacleGrid [i - 1 ][j ])
62
+ else :
63
+ obstacleGrid [i ][j ] += obstacleGrid [i - 1 ][j ]
64
+ else :
65
+ obstacleGrid [i ][j ] = 0
66
+ return obstacleGrid [- 1 ][- 1 ]
0 commit comments