Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 1fce563

Browse files
authored
Create 63. Unique Paths II.md
1 parent 2b97e89 commit 1fce563

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

63. Unique Paths II.md

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# 63. Unique Paths II
2+
3+
### 2020-07-30
4+
5+
A robot is located at the top-left corner of a *m* x *n* grid (marked 'Start' in the diagram below).
6+
7+
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).
8+
9+
Now consider if some obstacles are added to the grids. How many unique paths would there be?
10+
11+
![img](https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png)
12+
13+
An obstacle and empty space is marked as `1` and `0` respectively in the grid.
14+
15+
**Note:** *m* and *n* will be at most 100.
16+
17+
**Example 1:**
18+
19+
```
20+
Input:
21+
[
22+
[0,0,0],
23+
[0,1,0],
24+
[0,0,0]
25+
]
26+
Output: 2
27+
Explanation:
28+
There is one obstacle in the middle of the 3x3 grid above.
29+
There are two ways to reach the bottom-right corner:
30+
1. Right -> Right -> Down -> Down
31+
2. Down -> Down -> Right -> Right
32+
```
33+
34+
35+
# Solution
36+
37+
```swift
38+
class Solution {
39+
40+
func uniquePathsWithObstacles(_ obstacleGrid: [[Int]]) -> Int {
41+
let m = obstacleGrid.count
42+
guard m > 0 else {
43+
return 0
44+
}
45+
let n = obstacleGrid[0].count
46+
guard n > 0 else {
47+
return 0
48+
}
49+
var cache = [[Int]].init(repeating: [Int].init(repeating: 0, count: n), count: m)
50+
51+
for y in 1...m {
52+
for x in 1...n {
53+
if obstacleGrid[y - 1][x - 1] == 1 {
54+
cache[y - 1][x - 1] = 0
55+
} else if x == 1 {
56+
cache[y - 1][x - 1] = 1
57+
for _y in 1...y {
58+
if obstacleGrid[_y - 1][x - 1] == 1 {
59+
cache[y - 1][x - 1] = 0
60+
break
61+
}
62+
}
63+
} else if y == 1 {
64+
cache[y - 1][x - 1] = 1
65+
for _x in 1...x {
66+
if obstacleGrid[y - 1][_x - 1] == 1 {
67+
cache[y - 1][x - 1] = 0
68+
break
69+
}
70+
}
71+
} else {
72+
cache[y - 1][x - 1] = cache[y - 2][x - 1] + cache[y - 1][x - 2]
73+
}
74+
}
75+
}
76+
return cache[m - 1][n - 1]
77+
}
78+
}
79+
80+
```
81+

0 commit comments

Comments
 (0)