Minimum Falling Path Sum II Problem
Description
LeetCode Problem 1289.
Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts.
A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.
Example 1:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
Explanation:
The possible falling paths are:
[1,5,9], [1,5,7], [1,6,7], [1,6,8],
[2,4,8], [2,4,9], [2,6,7], [2,6,8],
[3,4,8], [3,4,9], [3,5,7], [3,5,9]
The falling path with the smallest sum is [1,5,7], so the answer is 13.
Example 2:
Input: grid = [[7]]
Output: 7
Constraints:
n == grid.length == grid[i].length1 <= n <= 200-99 <= grid[i][j] <= 99
Solution
Approach: Dynamic Programming With the Two Smallest Sums
Let f[j] be the minimum sum of a falling path through the rows processed so far that ends in column j. For the next row,
new_f[j] = row[j] + min(f[k] for k != j)
Computing that minimum naively costs O(n) per cell and O(n3) overall. We only ever need the smallest value of the previous row excluding one column, though, and that is either the smallest value (first, found in column first_col) or, when j == first_col, the second smallest (second). So per row we keep just these three numbers:
- for each column
j, computes = row[j] + (second if j == first_col else first); - track the smallest and second smallest
sof the new row, and where the smallest is.
Before the first row, first = second = 0 and first_col = -1, so every column of the first row just takes its own value. After the last row, first is the answer. Ties are handled naturally: if two columns share the smallest sum, second equals first, so excluding one of them changes nothing.
Complexity: O(n2) time and O(1) extra space.
class Solution:
def minFallingPathSum(self, grid: List[List[int]]) -> int:
# For the previous row keep the smallest path sum (first, in column first_col)
# and the second smallest (second). Column j adds to first unless j == first_col.
first, second, first_col = 0, 0, -1
for row in grid:
nfirst, nsecond, ncol = float("inf"), float("inf"), -1
for j, x in enumerate(row):
s = x + (second if j == first_col else first)
if s < nfirst:
nfirst, nsecond, ncol = s, nfirst, j
elif s < nsecond:
nsecond = s
first, second, first_col = nfirst, nsecond, ncol
return first