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
Input: matrix = [[2, 1, 3], [6, 5, 4], [7, 8, 9]]
Output: 13
Explanation: 1 → 5 → 7 or 1 → 4 → 8.
Example 2
Input: matrix = [[-19, 57], [-40, -5]]
Output: -59
Solution

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.

Left: the matrix of Example 1 with the falling path 1, 5, 7 highlighted. Right: the cheapest sum ending at each cell, with rows 2 1 3, then 7 6 5, then 13 13 14. The 13 in row 2, column 0 is 7 plus the smaller of the 7 and 6 above it.

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 prev, fills the current row into a new array named cur, and then lets cur take the place of prev.

Writing the new sums straight into prev would go wrong. Take the matrix [[0, 9], [8, 1]]. Filling row 1 in place, column 0 becomes 8 + 0 = 8 before column 1 is worked out. Column 1 then sees 8 above-left of it instead of 0, and the method returns 8. The correct answer is 1, from the path 0 → 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 works in these steps:

  1. First, copy the top row into prev with matrix[0].clone(). A path that starts in a column has collected only that cell's number so far. Copying also leaves the caller's matrix unchanged.
  2. Go down the remaining rows with a loop over r, starting at row 1. For each row, create a new array cur with one entry per column.
  3. Inside, a second loop moves c across the columns. It sets best to prev[c], the entry directly above. If c > 0 it also compares with prev[c - 1], and if c < n - 1 with prev[c + 1].
  4. Store matrix[r][c] + best in cur[c]. Once the whole row is filled, cur becomes prev for the next row.
  5. After the last row, a final loop over prev finds its smallest entry, answer, and the method returns it.

The main method runs both examples, a 1 Ɨ 1 matrix, the matrix [[0, 9], [8, 1]] that an in-place update gets wrong, and a 4 Ɨ 4 matrix with its 1s on the diagonal.

Java
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:

Output
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]], where the path 0 → 1 slides right; with prev updated in place, the same call returns 8. The last line, 4, is the four 1s of the diagonal, each one below-right of the one before.

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, prev and cur, are kept at a time instead of the whole n Ɨ n grid.

A triangle-shaped version with two choices per step is Triangle.