-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path063_uniquePathsWithObstacles.js
More file actions
80 lines (76 loc) · 1.44 KB
/
Copy path063_uniquePathsWithObstacles.js
File metadata and controls
80 lines (76 loc) · 1.44 KB
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
71
72
73
74
75
76
77
78
79
80
/**
* https://leetcode.cn/problems/unique-paths-ii/
* 不同路径II
*
* if(障碍物)
* f(i, j) = 0;
* else
* f(i, j) = f(i - 1, j) + f(i, j - 1);
*
* case 1: o(i, j)
* 0 0 0
* 0 1 0
* 0 0 0
*
* f(i, j)
* 1 1 1
* 1 0 1
* 1 1 2
*
* case 2: o(i, j)
* 0 1 0
* 0 0 0
* 0 0 0
*
* 1 0 0
* 1 1 1
* 1 2 3
*
* case 3
* 0 0
* 1 0
*
* 1 1
* 0 1
*
* case 4
* 0 0
* 1 1
* 0 0
*
* 1 1
* 0 0
* 0 0
*/
var uniquePathsWithObstacles = function(A) {
const m = A.length, n = A[0].length;
if (m < 1 || n < 1 || A[0][0] === 1 || A[m - 1][n - 1] === 1) return 0;
const obsIdx = A[0].indexOf(1);
// 初始化 dp
const dp = Array(n).fill(1);
const hasObs = obsIdx !== -1;
if (hasObs) {
for (let i = obsIdx; i < n; ++i) {
dp[i] = 0;
}
}
for (let i = 1; i < m; ++i) {
if (dp[0] != 0) { // 处理第一列
dp[0] = 1 - A[i][0];
}
for (let j = 1; j < n; ++j) {
if (A[i][j] === 1) {
dp[j] = 0;
} else {
dp[j] += dp[j - 1];
}
}
}
return dp[n - 1];
};
// ---- test case ----
console.log(uniquePathsWithObstacles([[0, 0, 0], [0, 1, 0], [0, 0, 0]])); // 2
console.log(uniquePathsWithObstacles([[0, 1, 0], [0, 0, 0], [0, 0, 0]])); // 3
console.log(uniquePathsWithObstacles([[0, 0], [1, 0]])); // 1
console.log(uniquePathsWithObstacles([[0, 1], [0, 0]])); // 1
console.log(uniquePathsWithObstacles([[0,0],[1,1],[0,0]])); // 0