File tree 2 files changed +106
-0
lines changed
2 files changed +106
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][]} A
3
+ * @return {number}
4
+ */
5
+ let minFallingPathSum = function (A) {
6
+ let n = A.length
7
+
8
+ let dp = []
9
+ for (let i = 0; i < n; i++) {
10
+ dp[i] = []
11
+ }
12
+
13
+ for (let j = 0; j < n; j++) {
14
+ dp[n - 1][j] = A[n - 1][j]
15
+ }
16
+
17
+ for (let i = n - 2; i >= 0; i--) {
18
+ for (let j = 0; j < n; j++) {
19
+ dp[i][j] = Infinity
20
+ let left = j - 1
21
+ let right = j + 1
22
+ let mid = j
23
+ let nextRowIndexes = [left, mid, right]
24
+ for (let nextRowIndex of nextRowIndexes) {
25
+ if (nextRowIndex >= 0 && nextRowIndex < n) {
26
+ dp[i][j] = Math.min(dp[i][j], A[i][j] + dp[i + 1][nextRowIndex])
27
+ }
28
+ }
29
+ }
30
+ }
31
+
32
+ // 第一行的最小值 可以确定整体的最小路径
33
+ return Math.min(...dp[0])
34
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][]} grid
3
+ * @return {number}
4
+ */
5
+ let uniquePathsIII = function (grid) {
6
+ let maxY = grid.length
7
+ if (!maxY) return 0
8
+ let maxX = grid[0].length
9
+
10
+ let validCellsCount = 0
11
+ let entry
12
+ let visited = []
13
+ for (let y = 0; y < maxY; y++) {
14
+ visited[y] = []
15
+ for (let x = 0; x < maxX; x++) {
16
+ let val = grid[y][x]
17
+ if (val === 0) {
18
+ validCellsCount++
19
+ }
20
+ if (val === 1) {
21
+ entry = [y, x]
22
+ }
23
+ }
24
+ }
25
+
26
+ let isValid = (y, x) => {
27
+ return (
28
+ y >= 0 &&
29
+ y < maxY &&
30
+ x >= 0 &&
31
+ x < maxX &&
32
+ !visited[y][x] &&
33
+ grid[y][x] !== -1
34
+ )
35
+ }
36
+
37
+ let dirs = [
38
+ [-1, 0],
39
+ [1, 0],
40
+ [0, -1],
41
+ [0, 1],
42
+ ]
43
+ let res = 0
44
+
45
+ let dfs = (y, x, passCount) => {
46
+ let val = grid[y][x]
47
+ if (val === 2) {
48
+ if (passCount === validCellsCount) {
49
+ res++
50
+ }
51
+ return
52
+ } else if (val === 0) {
53
+ passCount += 1
54
+ }
55
+
56
+ for (let [diffY, diffX] of dirs) {
57
+ let nextY = y + diffY
58
+ let nextX = x + diffX
59
+ if (isValid(nextY, nextX)) {
60
+ visited[nextY][nextX] = true
61
+ dfs(nextY, nextX, passCount)
62
+ visited[nextY][nextX] = false
63
+ }
64
+ }
65
+ }
66
+
67
+ let [entryY, entryX] = entry
68
+ visited[entryY][entryX] = true
69
+ dfs(entryY, entryX, 0)
70
+
71
+ return res
72
+ }
You can’t perform that action at this time.
0 commit comments