Minimum Falling Path Sum
Find the cheapest way down a square matrix by keeping, for every cell, the smallest sum that can reach it.
Given an n Ć n matrix of integers, return the smallest sum of a falling path through it. A falling path starts at any cell of the first row and goes down one row at a time. From each cell it moves to the cell directly below, below-left or below-right, staying inside the matrix.
Example 1
Output: 13
Explanation: 1 ā 5 ā 7 or 1 ā 4 ā 8.
Example 2
Output: -59
The Idea
Picture the matrix as a wall of numbered tiles, and a drop of water running down it from the top row. On each row the drop can fall straight down, or slide one tile to the left or right as it falls. Every tile it touches adds its number to a total, and we want the drop's route with the smallest total.
Take Example 1. Starting on the 1 in row 0, the drop can fall to the 5 below it and then slide left to the 7, for 1 + 5 + 7 = 13. It could also slide right to the 4 and fall to the 8, which gives 13 as well. But how do we know that no other route is cheaper? This 3 Ć 3 matrix has 17 falling paths, and with every extra row each path can split up to three ways.
Look at one cell instead of whole routes: the 7 in row 2, column 0. A drop can only arrive there from row 1, column 0 or column 1. Whatever it did before that matters only through what it has collected by then. So if we knew the cheapest sum of a path ending at each cell of row 1, the cheapest path ending at the 7 would follow from just two numbers.
That suggests writing, for every cell, the cheapest sum of a falling path that ends there. Look at the picture below. The left grid is the matrix, with the route 1 ā 5 ā 7 in orange. The right grid, labelled "cheapest sum ending here", holds those sums.
Row 0 of the right grid copies the matrix, because a path that starts there has collected only that one number. In row 1, the 6 of the matrix can be reached from the 2 or the 1 above, so its entry is 6 + 1 = 7. The 5 can be reached from 2, 1 or 3, giving 5 + 1 = 6, and the 4 from 1 or 3, giving 4 + 1 = 5.
Now row 2, column 0. The two teal cells above it hold 7 and 6. Its entry is the matrix's 7 plus the smaller of those, 6, so 7 + 6 = 13, as the orange label says. The rest of row 2 fills in the same way, and its entries are 13, 13 and 14. A path may end in any column, so the answer is the smallest of them: 13.
Each entry was worked out once, from entries in the row above that were already final, and no route was ever followed from the top. Solving the problem by filling such a grid of smaller answers is called dynamic programming.
Solution Approach
Trying every falling path works but grows too quickly, which is why the code fills the grid of cheapest sums instead. That leaves three things to settle: how much of the grid to keep, how to treat cells at the left and right edges, and where the answer is.
Trying every path
Why not follow every route from the top and keep the smallest total? In Example 1 that means 17 paths. Each new row lets a path continue in up to three directions, so a matrix of 20 rows can have up to 20 Ć 319 paths, about 23 billion. The grid of cheapest sums for the same matrix has only 400 entries, and each one looks at no more than three entries above it.
Keeping one row at a time
Do we need the whole grid? Each entry reads only the row directly above it, so two rows are enough. The code keeps the finished row above in an array named prevcurcurprev
Writing the new sums straight into prev[[0, 9], [8, 1]]
Cells at the left and right edges
What about the cells in the first and last columns? A cell in column 0 has nothing above-left of it, and a cell in the last column has nothing above-right. So the code always starts from the cell directly above and compares with a side neighbour only when that column exists inside the matrix.
Where the answer is
Which entry is the answer? A falling path may end in any column of the last row, so the answer is the smallest entry of that row. For a 1 Ć 1 matrix there are no rows to fill, and the answer is the single number itself.
Java Solution
The method minFallingPathSum
- First, copy the top row into
withprev . A path that starts in a column has collected only that cell's number so far. Copying also leaves the caller's matrix unchanged.matrix[0].clone() - Go down the remaining rows with a loop over
, starting at row 1. For each row, create a new arrayr with one entry per column.cur - Inside, a second loop moves
across the columns. It setsc tobest , the entry directly above. Ifprev[c] it also compares withc > 0 , and ifprev[c - 1] withc < n - 1 .prev[c + 1] - Store
inmatrix[r][c] + best . Once the whole row is filled,cur[c] becomescur for the next row.prev - After the last row, a final loop over
finds its smallest entry,prev , and the method returns it.answer
The main[[0, 9], [8, 1]]
public class MinimumFallingPathSum {
public static int minFallingPathSum(int[][] matrix) {
int n = matrix.length;
int[] prev = matrix[0].clone(); // cheapest sums ending in each cell of the row above
for (int r = 1; r < n; r++) {
int[] cur = new int[n];
for (int c = 0; c < n; c++) {
int best = prev[c]; // from directly above
if (c > 0) {
best = Math.min(best, prev[c - 1]); // from above-left
}
if (c < n - 1) {
best = Math.min(best, prev[c + 1]); // from above-right
}
cur[c] = matrix[r][c] + best;
}
prev = cur;
}
int answer = Integer.MAX_VALUE;
for (int v : prev) {
answer = Math.min(answer, v);
}
return answer;
}
public static void main(String[] args) {
System.out.println(minFallingPathSum(new int[][] {{2, 1, 3}, {6, 5, 4}, {7, 8, 9}}));
System.out.println(minFallingPathSum(new int[][] {{-19, 57}, {-40, -5}}));
System.out.println(minFallingPathSum(new int[][] {{7}}));
System.out.println(minFallingPathSum(new int[][] {{0, 9}, {8, 1}}));
System.out.println(minFallingPathSum(new int[][] {
{1, 9, 9, 9}, {9, 1, 9, 9}, {9, 9, 1, 9}, {9, 9, 9, 1}}));
}
}
Running it prints:
13
-59
7
1
4
Look at the first line: 13, the smallest of the last row 13, 13 and 14 in the picture. The -59 of Example 2 comes from -19 in row 0 and the -40 directly below it, since -40 + (-19) is smaller than -40 + 57.
The 7 is the 1 Ć 1 matrix: the loop over rows never runs, so the answer is the copied top row. The 1 on the fourth line comes from [[0, 9], [8, 1]]prev
Complexity
The work is one entry per cell below the top row, plus a scan of the last row.
- Time: O(n²), because each of the n - 1 lower rows fills n entries, every entry compares at most three sums from the row above, and the final scan reads n more.
- Space: O(n), because only two rows of cheapest sums,
andprev , are kept at a time instead of the whole n Ć n grid.cur
A triangle-shaped version with two choices per step is