一个机器人位于一个 m x n 网格的左上角。机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角。现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?网格中的障碍物和空位置分别用 1 和 0 来表示。
示例 1:
输入:obstacleGrid = [ [0,0,0],[0,1,0],[0,0,0] ]
输出:2示例 2:
输入:obstacleGrid = [ [0,1],[0,0] ]
输出:1动态规划解法:
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71object UniquePathsWithObstacles {
def main(args: Array[String]): Unit = {
println(
uniquePathsWithObstacles(Array(Array(0, 1), Array(0, 0)))
)
println(
uniquePathsWithObstacles(Array(Array(0, 0, 0, 0)))
)
println(
uniquePathsWithObstacles(Array(Array(0, 1, 0, 0)))
)
println(
uniquePathsWithObstacles(Array(Array(0, 0), Array(0, 1)))
)
println(
uniquePathsWithObstacles(Array(Array(0, 0, 0), Array(0, 1, 0), Array(0, 0, 0)))
)
}
/**
* 动态规划,时间复杂度O(m*n),空间复杂度O(m*n)
*/
def uniquePathsWithObstacles(obstacleGrid: Array[Array[Int]]): Int = {
val m = obstacleGrid.length
val n = obstacleGrid(0).length
if (obstacleGrid(0)(0) == 1) return 0
if (m == 1 && n == 1 && obstacleGrid(0)(0) == 0) return 1
val dp = new Array[Array[Int]](m)
for (i <- 0 until m) {
dp(i) = new Array[Int](n)
for (j <- 0 until n) {
dp(i)(j) = if (obstacleGrid(i)(j) == 0) 0 else Int.MaxValue
}
}
dp(0)(0) = 0
for (i <- 1 until m) {
if (dp(i)(0) != Int.MaxValue) {
dp(i)(0) = if (dp(i - 1)(0) == Int.MaxValue) Int.MaxValue else 1
}
}
for (i <- 1 until n) {
if (dp(0)(i) != Int.MaxValue) {
dp(0)(i) = if (dp(0)(i - 1) == Int.MaxValue) Int.MaxValue else 1
}
}
for (i <- 1 until m) {
for (j <- 1 until n) {
if (dp(i)(j) != Int.MaxValue) {
if (dp(i - 1)(j) == Int.MaxValue && dp(i)(j - 1) == Int.MaxValue) {
dp(i)(j) = Int.MaxValue
} else {
if (dp(i - 1)(j) != Int.MaxValue) dp(i)(j) += dp(i - 1)(j)
if (dp(i)(j - 1) != Int.MaxValue) dp(i)(j) += dp(i)(j - 1)
}
}
}
}
if (dp(m - 1)(n - 1) == Int.MaxValue) 0 else dp(m - 1)(n - 1)
}
}