Minimum Falling Path Sum II LeetCode solution in JavaScript

1
var minFallingPathSum = function (grid) {
2
if (grid.length === 1) {
3
return grid[0][0];
4
}
5
let sums = []; //find first, second and third minimum values in the grid as these are only possible values for path
6
//store the index for fast lookup in a 3D array
7
for (let i = 0; i < grid.length; i++) {
8
let min = Math.min(...grid[i]);
9
let idx = grid[i].indexOf(min);
10
grid[i].splice(idx, 1, Infinity);
11
let min2 = Math.min(...grid[i]);
12
let idx2 = grid[i].indexOf(min2);
13
grid[i].splice(idx2, 1, Infinity);
14
let min3 = Math.min(...grid[i]);
15
let idx3 = grid[i].indexOf(min3);
16
sums.push([
17
[min, idx],
18
[min2, idx2],
19
[min3, idx3],
20
]);
21
}
22
// sums contains 1st , 2nd and 3rd min value and index
23
let memo = {}; // for memoization
24
let recur = (r, li) => {
25
//recursive call to decide which path to choose from r=row, li=lastIndex
26
if (memo[r + "," + li] !== undefined) {
27
// memoized
28
return memo[r + "," + li];
29
}
30
if (r === grid.length - 1) {
31
// last and first choice for path can only be from 1st and 2nd minimum, as there is only one other row to occupy these columns
32
if (li === sums[r][0][1]) {
33
memo[r + "," + li] = sums[r][1][0];
34
} else {
35
memo[r + "," + li] = sums[r][0][0];
36
}
37
return memo[r + "," + li];
38
} else {
39
switch (
40
li // pick the minimum value path where index is not equal to last index
41
) {
42
case sums[r][0][1]:
43
memo[r + "," + li] = Math.min(
44
sums[r][1][0] + recur(r + 1, sums[r][1][1]),
45
sums[r][2][0] + recur(r + 1, sums[r][2][1])
46
);
47
break;
48
case sums[r][1][1]:
49
memo[r + "," + li] = Math.min(
50
sums[r][0][0] + recur(r + 1, sums[r][0][1]),
51
sums[r][2][0] + recur(r + 1, sums[r][2][1])
52
);
53
break;
54
case sums[r][2][1]:
55
memo[r + "," + li] = Math.min(
56
sums[r][1][0] + recur(r + 1, sums[r][1][1]),
57
sums[r][0][0] + recur(r + 1, sums[r][0][1])
58
);
59
break;
60
default:
61
memo[r + "," + li] = Math.min(
62
sums[r][0][0] + recur(r + 1, sums[r][0][1]),
63
sums[r][1][0] + recur(r + 1, sums[r][1][1]),
64
sums[r][2][0] + recur(r + 1, sums[r][2][1])
65
);
66
}
67
return memo[r + "," + li];
68
}
69
};
70
return recur(0, sums[0][2][1]); //since first and last can only be picked from 1st and 2nd min values
71
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0