Problem Description
Given an n x n integer matrix, return the minimum sum of a falling path with non-zero shifts. A falling path picks exactly one element from each row such that no two adjacent rows pick an element from the same column.
Key Insights
- Use dynamic programming to compute the minimum falling path sum row by row.
- Instead of checking all columns in the previous row for every cell, track the smallest and second smallest sums from the previous row.
- If the current cell's column is the same as the column with the smallest previous sum, use the second smallest; otherwise, use the smallest.
- This optimization reduces the inner loop computation and improves efficiency.
- Handle the edge case when the matrix size is 1.
Space and Time Complexity
Time Complexity: O(n^2)
Space Complexity: O(n) if using a one-dimensional DP array (can also be done in-place)
Solution
We use a dynamic programming approach where dp[i][j] represents the minimum sum of a falling path ending in cell (i, j) in row i. For each row i, we compute two values from the previous row: the smallest sum (min1) and the second smallest sum (min2) along with their column indices. For the current cell, if its column is the same as the column of min1, then we add min2 from the previous row; otherwise, we add min1. This avoids the need to iterate over all columns for each cell when updating the current row, leading to significant optimization for larger matrices.