Minimum sum falling path in a NxN grid | Python3 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 code ; function to print required answer
import sys NEW_LINE n = 3 NEW_LINE def minFallingPathSum ( A ) : NEW_LINE INDENT for R in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT for C in range ( n ) : NEW_LINE INDENT best = A [ R + 1 ] [ C ] NEW_LINE if C > 0 : NEW_LINE INDENT best = min ( best , A [ R + 1 ] [ C - 1 ] ) NEW_LINE DEDENT if C + 1 < n : NEW_LINE INDENT best = min ( best , A [ R + 1 ] [ C + 1 ] ) NEW_LINE DEDENT A [ R ] [ C ] = A [ R ] [ C ] + best NEW_LINE DEDENT DEDENT ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = min ( ans , A [ 0 ] [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE print ( minFallingPathSum ( A ) ) NEW_LINE DEDENT