Skip to content

Commit c92b697

Browse files
committed
Add solution #931
1 parent f8957e3 commit c92b697

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,7 @@
740740
928|[Minimize Malware Spread II](./solutions/0928-minimize-malware-spread-ii.js)|Hard|
741741
929|[Unique Email Addresses](./solutions/0929-unique-email-addresses.js)|Easy|
742742
930|[Binary Subarrays With Sum](./solutions/0930-binary-subarrays-with-sum.js)|Medium|
743+
931|[Minimum Falling Path Sum](./solutions/0931-minimum-falling-path-sum.js)|Medium|
743744
933|[Number of Recent Calls](./solutions/0933-number-of-recent-calls.js)|Easy|
744745
937|[Reorder Data in Log Files](./solutions/0937-reorder-data-in-log-files.js)|Medium|
745746
966|[Vowel Spellchecker](./solutions/0966-vowel-spellchecker.js)|Medium|
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 931. Minimum Falling Path Sum
3+
* https://leetcode.com/problems/minimum-falling-path-sum/
4+
* Difficulty: Medium
5+
*
6+
* Given an n x n array of integers matrix, return the minimum sum of any falling path
7+
* through matrix.
8+
*
9+
* A falling path starts at any element in the first row and chooses the element in the
10+
* next row that is either directly below or diagonally left/right. Specifically, the
11+
* next element from position (row, col) will be (row + 1, col - 1), (row + 1, col),
12+
* or (row + 1, col + 1).
13+
*/
14+
15+
/**
16+
* @param {number[][]} matrix
17+
* @return {number}
18+
*/
19+
var minFallingPathSum = function(matrix) {
20+
let previousRow = [...matrix[0]];
21+
22+
for (let row = 1; row < matrix.length; row++) {
23+
const currentRow = new Array(matrix.length);
24+
for (let col = 0; col < matrix.length; col++) {
25+
const leftDiagonal = col > 0 ? previousRow[col - 1] : Infinity;
26+
const directlyAbove = previousRow[col];
27+
const rightDiagonal = col < matrix.length - 1 ? previousRow[col + 1] : Infinity;
28+
currentRow[col] = matrix[row][col] + Math.min(leftDiagonal, directlyAbove, rightDiagonal);
29+
}
30+
previousRow = currentRow;
31+
}
32+
33+
return Math.min(...previousRow);
34+
};

0 commit comments

Comments
 (0)