Minimum Falling Path Sum Problem
Description
LeetCode Problem 931.
Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.
A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).
Example 1:
Input: matrix = [[2,1,3],[6,5,4],[7,8,9]]
Output: 13
Explanation: There are two falling paths with a minimum sum as shown.
Example 2:
Input: matrix = [[-19,57],[-40,-5]]
Output: -59
Explanation: The falling path with a minimum sum is shown.
Constraints:
- n == matrix.length == matrix[i].length
- 1 <= n <= 100
- -100 <= matrix[i][j] <= 100
Solution
Approach: Row-by-Row Dynamic Programming
Trying every falling path explores up to 3n paths, but they overlap heavily: the cheapest way to reach a cell only depends on the cheapest ways to reach the three cells above it.
Let best[c] be the smallest sum of a falling path that ends at column c of the current row.
- For the first row,
bestis the row itself. - For each next row, compute
next_best[c] = matrix[row][c] + min(best[c - 1], best[c], best[c + 1]), using only the neighbors that exist: the first and last columns have just two cells above them. - After the last row, the answer is the smallest value in
best, since a path may end in any column.
Only the previous row is needed, so one array is kept instead of the full table. A new array is filled for each row; updating best in place would overwrite best[c - 1] before column c reads it.
For example 1, the rows give best = [2,1,3], then [7,6,5], then [13,13,14], so the answer is 13.
Complexity: O(n2) time and O(n) extra space, where n is the size of the matrix.
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
best = matrix[0][:] # best[c] = smallest path sum ending at column c of the current row
for row in range(1, n):
next_best = [0] * n
for col in range(n):
# The path can come from the column above, or one to its left or right.
above = best[col]
if col > 0:
above = min(above, best[col - 1])
if col < n - 1:
above = min(above, best[col + 1])
next_best[col] = matrix[row][col] + above
best = next_best
return min(best)
Now write it from memory
Close the write-up and solve it yourself against the tests.