Minimum Falling Path Sum

Pattern: 2D grid DP

medium

A falling path takes one cell per row, moving to the same column or one to the side. The cheapest path ending at a cell is its value plus the cheapest of the three cells above it.

The problem

Given an n × n matrix, return the smallest sum of a path that starts in the top row and moves down one row at a time to the cell below, below-left or below-right.

Think first

  • From which cells can you reach (r, c)?
  • What do you need from the row above?
  • Where does the answer come from?

Hints

    Brute force, and why it fails

    Try every path: 3ⁿ.

    The key insight

    Each row's best values depend only on the previous row's.

    Dry run

    best2 1 3

    matrix [[2, 1, 3], [6, 5, 4], [7, 8, 9]]. Row 0: 2 1 3.

    Step 1 of 3

    The plan

    best = row 0
    for each row: best[c] = row[c] + min(best[c-1], best[c], best[c+1])
    return min(best)
    

    Complexity

    Time
    O(n²)
    Space
    O(n)

    Each cell checks three.

    Edge cases

    • 1 × 1.
    • Negative values.
    • Edges of the row.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int minFallingPathSum(int[][] matrix) {
            int n = matrix.length;
            int[] best = matrix[0].clone();         // best[c]: the cheapest path ending at column c of the current row
            for (int r = 1; r < n; r++) {
                int[] next = new int[n];
                for (int c = 0; c < n; c++) {
                    int m = best[c];                // from directly above or diagonally above
                    if (c > 0) m = Math.min(m, best[c - 1]);
                    if (c < n - 1) m = Math.min(m, best[c + 1]);
                    next[c] = m + matrix[r][c];
                }
                best = next;
            }
            return Arrays.stream(best).min().getAsInt();
        }
    }

    C++

    class Solution {
    public:
        int minFallingPathSum(vector<vector<int>>& matrix) {
            int n = static_cast<int>(matrix.size());
            vector<int> best(matrix[0]);            // best[c]: the cheapest path ending at column c of the current row
            for (int r = 1; r < n; r++) {
                vector<int> next(n);
                for (int c = 0; c < n; c++) {
                    int m = best[c];                // from directly above or diagonally above
                    if (c > 0) m = min(m, best[c - 1]);
                    if (c < n - 1) m = min(m, best[c + 1]);
                    next[c] = m + matrix[r][c];
                }
                best = next;
            }
            return *min_element(best.begin(), best.end());
        }
    };

    Python

    class Solution:
        def minFallingPathSum(self, matrix: list[list[int]]) -> int:
            best = list(matrix[0])                  # best[c]: the cheapest path ending at column c of the current row
            n = len(best)
            for row in matrix[1:]:
                best = [row[c] + min(best[max(c - 1, 0):c + 2]) for c in range(n)]   # from above or diagonally above
            return min(best)

    Common mistakes

    • Reading outside the row.
    • Overwriting best while reading it.

    Similar problems