SDE & MLE Prep

931. Minimum Falling Path Sum

Problem

A falling path starts at any cell of the first row of the n×n matrix and moves to the next row's cell directly below or diagonally left/right. Return the minimum sum of a falling path.

Example: [[2,1,3],[6,5,4],[7,8,9]] → 13

Row by row: dp[c] = matrix[r][c] + min(prev[c−1], prev[c], prev[c+1]).

Complexity: O(n²).

class Solution:
    def minFallingPathSum(self, matrix: List[List[int]]) -> int:
        prev = matrix[0][:]
        n = len(prev)
        for row in matrix[1:]:
            prev = [row[c] + min(prev[max(0, c - 1):c + 2]) for c in range(n)]
        return min(prev)