Problem Description
Given an n x n matrix of integers, we must find the minimum sum of any falling path. A falling path starts at any element in the first row and moves to the next row choosing an element directly below or diagonally left/right.
Key Insights
- Use dynamic programming to calculate the minimum path sum from bottom to top.
- For each cell, only consider the three possible moves in the next row (down, down-left, down-right), making sure to handle boundary conditions.
- A bottom-up approach allows us to build the solution by using the already computed results of the subproblems.
- The final result is the minimum value in the computed first row.
Space and Time Complexity
Time Complexity: O(n^2) because each of the n*n elements is processed once. Space Complexity: O(n^2) using an auxiliary DP matrix, though the solution can be optimized to O(1) extra space by updating the matrix in-place.
Solution
We solve this problem using dynamic programming with a bottom-up approach. We initialize a DP structure (or update the matrix in-place) that stores the minimum falling path sum from each cell to the bottom row. Starting from the second last row, we iterate upward. For each cell (i, j), we add the current cell value with the minimum of the allowed moves from the row below (directly below, diagonally left, and diagonally right). Consider boundary conditions for the first and last columns. The answer is the minimum value found in the top row after processing.