Minimum sum falling path in a NxN grid | Javascript Program to minimum required sum ; Function to return minimum path falling sum ; R = Row and C = Column We begin from second last row and keep adding maximum sum . ; best = min ( A [ R + 1 ] [ C - 1 ] , A [ R + 1 ] [ C ] , A [ R + 1 ] [ C + 1 ] ) ; Driver program ; function to print required answer
let n = 3 ; function minFallingPathSum ( A ) { for ( let R = n - 2 ; R >= 0 ; -- R ) { for ( let C = 0 ; C < n ; ++ C ) { let best = A [ R + 1 ] [ C ] ; if ( C > 0 ) best = Math . min ( best , A [ R + 1 ] [ C - 1 ] ) ; if ( C + 1 < n ) best = Math . min ( best , A [ R + 1 ] [ C + 1 ] ) ; A [ R ] [ C ] = A [ R ] [ C ] + best ; } } let ans = Number . MAX_VALUE ; for ( let i = 0 ; i < n ; ++ i ) ans = Math . min ( ans , A [ 0 ] [ i ] ) ; return ans ; } let A = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; document . write ( minFallingPathSum ( A ) ) ;