
Problem Statement
The goal of this problem is to find the minimum sum of a falling path through an n x n
integer matrix. A falling path begins at any cell in the first row and proceeds to a cell in the next row, directly below or diagonally adjacent (left or right). As the path progresses through each subsequent row following these rules, we add the values of the selected cells. The objective is to determine the path that has the least combined value of the selected cells from top to bottom.
Examples
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
Approach and Intuition
To solve this problem, analyzing how we can traverse through the matrix using dynamic programming proves beneficial. Here are the steps for deciphering the minimum falling path sum:
Begin by understanding that each cell
(row, col)
in the matrix can be reached from its above row from three potential cells: directly above(row - 1, col)
, diagonally left(row - 1, col - 1)
ifcol > 0
, and diagonally right(row - 1, col + 1)
ifcol < n - 1
.To compute the minimum path sum for each cell, you require the minimum of the potential cells above it.
Start from the second row and update each cell with the sum of its own value and the minimum value from the possible paths above.
After populating the matrix with the above approach, the bottom row of the matrix then contains the minimal sums of falling paths that end at each cell in that row.
Lastly, scanning the bottom row will give the minimum sum of the falling paths through the matrix as it contains the minimal values after considering all possible paths.
By understanding these steps, we can appreciate how dynamic programming cleverly uses previously computed values to operationalize and solve complex problems efficiently, thereby allowing us to find the minimal falling path sum without testing each possible path explicitly.
Example Understanding:
For the given
matrix = [[2,1,3],[6,5,4],[7,8,9]]
: starting from the first row, the optimal choice would involve following down the middle of the matrix taking 1 from the first row, 4 from the second, and then 8 from the third resulting in a sum of 13.For
matrix = [[-19,57],[-40,-5]]
: choosing the leftmost path involving -19 from the first row and -40 from the second yields the best (minimum) result of -59.
Solutions
- C++
- Java
class Solution {
public:
int calculateMinPathSum(vector<vector<int>>& grid) {
vector<int> pathSum(grid.size() + 1, 0);
for (int i = grid.size() - 1; i >= 0; i--) {
vector<int> currentPath(grid.size() + 1, 0);
for (int j = 0; j < grid.size(); j++) {
if (j == 0) {
currentPath[j] = min(pathSum[j], pathSum[j + 1]) + grid[i][j];
} else if (j == grid.size() - 1) {
currentPath[j] = min(pathSum[j], pathSum[j - 1]) + grid[i][j];
} else {
currentPath[j] = min({pathSum[j], pathSum[j - 1], pathSum[j + 1]}) + grid[i][j];
}
}
pathSum = currentPath;
}
int minimumPathSum = INT_MAX;
for (int startIndex = 0; startIndex < grid.size(); startIndex++) {
minimumPathSum = min(minimumPathSum, pathSum[startIndex]);
}
return minimumPathSum;
}
};
Developing an efficient solution to compute the minimum falling path sum through a matrix arrays, the provided C++ code offers an intuitive yet effective approach using dynamic programming.
Start by initializing a vector
pathSum
with length one greater than the matrix size, filled with zeros. This vector will hold the minimum path sum from the last row to the current row during iteration.Iterate through the matrix from the bottom row to the top row. For each row, initialize a temporary vector
currentPath
of the same size aspathSum
to store the minimum path sums concluding at each cell of the current row.For each element in the current row, calculate the minimum path sum using the results from the previous row (
pathSum
). If the element is in:- The first column, consider the sum coming from directly above or from the upper right.
- The last column, consider the sum coming from directly above or from the upper left.
- Any other column, consider sums coming from directly above, upper left, and upper right.
Update
pathSum
withcurrentPath
after processing each row, makingpathSum
ready for the next iteration.After completing the iteration over all rows, the final step involves finding the smallest value in
pathSum
to determine the minimum path sum from top to bottom.
The solution efficiently computes the required result by iterating over the matrix only once and using a dynamic programming array to store interim results, significantly reducing the computational complexity. Ensure to include all necessary headers such as <vector>
and <algorithm>
to utilize std::min
, and define Solution
class and calculateMinPathSum
method in a manner compatible with your broader program structure.
class Solution {
public int minimumFallingPathSum(int[][] grid) {
int n = grid.length;
int[] previous = new int[n + 1];
for (int i = n - 1; i >= 0; i--) {
int[] current = new int[n + 1];
for (int j = 0; j < n; j++) {
if (j == 0) {
current[j] = Math.min(previous[j], previous[j + 1]) + grid[i][j];
} else if (j == n - 1) {
current[j] = Math.min(previous[j], previous[j - 1]) + grid[i][j];
} else {
current[j] = Math.min(previous[j], Math.min(previous[j + 1], previous[j - 1])) + grid[i][j];
}
}
previous = current;
}
int minimumPathSum = Integer.MAX_VALUE;
for (int col = 0; col < n; col++) {
minimumPathSum = Math.min(minimumPathSum, previous[col]);
}
return minimumPathSum;
}
}
The provided Java solution efficiently calculates the minimum falling path sum for a given square matrix grid
. The approach utilizes dynamic programming to minimize memory usage and complexity. Here’s a breakdown of the implementation:
- A 1D array
previous
is used to store the minimum path sums of the previous row. This reduces space complexity compared to using a full 2D array. - The algorithm iterates from the bottom row of the grid upwards. For each cell, it calculates the sum of the cell value and the minimum path sum from the potential previous positions—directly above, above-left, or above-right, managing edge cases for the first and last columns where fewer choices exist.
- After populating the
previous
array, the algorithm finds the minimum value inprevious
, which represents the minimum path sum from the top of the matrix to any bottom cell.
The process ensures efficient computation by scanning each column of every row only once and updating the path sum in constant time. This blend of a bottom-up dynamic programming strategy with careful boundary checking ensures both correctness and performance for large matrices.
No comments yet.