-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0931-minimum-falling-path-sum.js
More file actions
38 lines (32 loc) · 964 Bytes
/
0931-minimum-falling-path-sum.js
File metadata and controls
38 lines (32 loc) · 964 Bytes
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
/**
* Minimum Falling Path Sum
* Time Complexity: O(N^2)
* Space Complexity: O(N)
*/
var minFallingPathSum = function (matrix) {
const gridSize = matrix.length;
if (gridSize === 1) {
return matrix[0][0];
}
let lastRowMinima = [...matrix[0]];
let rowIter = 1;
while (rowIter < gridSize) {
const thisRowMinima = new Array(gridSize);
const actualMatrixRow = matrix[rowIter];
let colIter = 0;
while (colIter < gridSize) {
const leftOption = colIter > 0 ? lastRowMinima[colIter - 1] : Infinity;
const centerOption = lastRowMinima[colIter];
const rightOption =
colIter < gridSize - 1 ? lastRowMinima[colIter + 1] : Infinity;
thisRowMinima[colIter] =
actualMatrixRow[colIter] +
Math.min(leftOption, centerOption, rightOption);
colIter++;
}
lastRowMinima = thisRowMinima;
rowIter++;
}
const resultMinSum = Math.min(...lastRowMinima);
return resultMinSum;
};