sagelearnai

Minimum Falling Path Sum

Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #931

A falling path starts at any cell in the first row and moves down one row each step, to the cell directly below or diagonally below-left or below-right. Return the minimum sum of a falling path through the n × n matrix.

Examples

text
[[2,1,3],[6,5,4],[7,8,9]]  →  13   (1→5→7 or 1→4→8)
[[-19,57],[-40,-5]]         →  -59

Hints

  1. Each cell can be reached from up to three cells in the previous row.

Approach

Roll a 1-D prev row: cur[c] = m[r][c] + min(prev[c−1], prev[c], prev[c+1]) (skipping the out-of-range ones). The answer is min(prev) after the last row. O(n²) time, O(n) space.

Complexity

Time: O(n²). Space: O(n).

Python solution
def minFallingPathSum(matrix):
    prev = matrix[0][:]
    n = len(matrix)
    for r in range(1, n):
        prev = [matrix[r][c] + min(prev[max(0, c - 1):c + 2]) for c in range(n)]
    return min(prev)
JavaScript solution
function minFallingPathSum(matrix) {
  const n = matrix.length;
  let prev = [...matrix[0]];
  for (let r = 1; r < n; r++) {
    const cur = new Array(n);
    for (let c = 0; c < n; c++) {
      let best = prev[c];
      if (c > 0) best = Math.min(best, prev[c - 1]);
      if (c + 1 < n) best = Math.min(best, prev[c + 1]);
      cur[c] = matrix[r][c] + best;
    }
    prev = cur;
  }
  return Math.min(...prev);
}