Skip to content

Commit bb20cd5

Browse files
committed
Update solution to unique path ii
1 parent 236fc3a commit bb20cd5

File tree

1 file changed

+20
-28
lines changed

1 file changed

+20
-28
lines changed

DP/UniquePathsII.swift

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,37 +5,29 @@
55
*/
66

77
class UniquePathsII {
8-
func uniquePathsWithObstacles(_ obstacleGrid: [[Int]]) -> Int {
9-
let m = obstacleGrid.count
10-
guard m > 0 else {
11-
return 0
12-
}
8+
func uniquePathsWithObstacles(_ obstacleGrid: [[Int]]) -> Int {
9+
let m = obstacleGrid.count, n = obstacleGrid[0].count
1310

14-
let n = obstacleGrid[0].count
15-
guard n > 0 else {
16-
return 0
17-
}
18-
19-
var dp = Array(repeating: Array(repeating: -1, count: n), count: m)
11+
var dp = Array(repeating: Array(repeating: 0, count: n), count: m)
2012

21-
return help(m - 1, n - 1, &dp, obstacleGrid)
22-
}
23-
24-
fileprivate func help(_ m: Int, _ n: Int, _ dp: inout [[Int]], _ obstacleGrid: [[Int]]) -> Int {
25-
if m < 0 || n < 0 {
26-
return 0
27-
}
28-
if obstacleGrid[m][n] == 1 {
29-
return 0
30-
}
31-
if m == 0 && n == 0 {
32-
return 1
33-
}
34-
if dp[m][n] != -1 {
35-
return dp[m][n]
13+
for i in 0..<m {
14+
for j in 0..<n {
15+
if obstacleGrid[i][j] == 1 {
16+
dp[i][j] = 0
17+
} else {
18+
if i == 0 && j == 0 {
19+
dp[i][j] = 1
20+
} else if i == 0 {
21+
dp[i][j] = dp[i][j - 1]
22+
} else if j == 0 {
23+
dp[i][j] = dp[i - 1][j]
24+
} else {
25+
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
26+
}
27+
}
28+
}
3629
}
3730

38-
dp[m][n] = help(m - 1, n, &dp, obstacleGrid) + help(m, n - 1, &dp, obstacleGrid)
39-
return dp[m][n]
31+
return dp[m - 1][n - 1]
4032
}
4133
}

0 commit comments

Comments
 (0)