File tree 1 file changed +29
-0
lines changed
scripts/algorithms/M/Minimum Falling Path Sum
1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 74 ms (Top 20.39%) | Memory: 44.70 MB (Top 31.58%)
2
+
3
+ var minFallingPathSum = function ( matrix ) {
4
+ let n = matrix . length ;
5
+ let m = matrix [ 0 ] . length ;
6
+ let dp = new Array ( n ) . fill ( 0 ) . map ( ( ) => new Array ( m ) . fill ( 0 ) ) ;
7
+
8
+ // tabulation // bottom-up approach
9
+
10
+ // base case - when i will be 0, dp[0][j] will be matrix[0][j]
11
+ for ( let j = 0 ; j < m ; j ++ ) dp [ 0 ] [ j ] = matrix [ 0 ] [ j ]
12
+
13
+ for ( let i = 1 ; i < n ; i ++ ) {
14
+ for ( let j = 0 ; j < m ; j ++ ) {
15
+ let up = matrix [ i ] [ j ] + dp [ i - 1 ] [ j ] ;
16
+
17
+ let upLeft = matrix [ i ] [ j ] ;
18
+ if ( ( j - 1 ) >= 0 ) upLeft += dp [ i - 1 ] [ j - 1 ] ; // if not out of bound
19
+ else upLeft += 10000 ; // big enough number
20
+
21
+ let upRight = matrix [ i ] [ j ] ;
22
+ if ( ( j + 1 ) < m ) upRight += dp [ i - 1 ] [ j + 1 ] ; // if not out of bound
23
+ else upRight += 10000 ; // big enough number
24
+
25
+ dp [ i ] [ j ] = Math . min ( up , upLeft , upRight ) ;
26
+ }
27
+ }
28
+ return Math . min ( ...dp [ n - 1 ] ) ;
29
+ } ;
You can’t perform that action at this time.
0 commit comments