Minimum Path Sum

Find the smallest sum along a path from the top-left to the bottom-right of a grid, moving only right or down.

Given a grid of non-negative numbers with m rows and n columns, find a path from the top-left cell to the bottom-right cell whose numbers add up to the smallest possible sum, and return that sum. Each move goes one cell to the right or one cell down, and the first and last cells count too.

Example 1
Input: grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
Output: 7
Explanation: the path 1 → 3 → 1 → 1 → 1 adds up to 7.
Example 2
Input: grid = [[1, 2, 3], [4, 5, 6]]
Output: 12
Solution

The Idea

Picture the grid as a floor of tiles, with a toll written on each tile. You start on the top-left tile and walk to the bottom-right one, one step right or down at a time, paying the toll of every tile you stand on. In Example 1 the cheapest walk, 1 → 3 → 1 → 1 → 1, costs 7.

A natural first try is to always step onto the cheaper of the two next tiles. From the 1 in the top-left corner, the tile below costs 1 and the tile to the right costs 3, so it steps down. Next it steps down onto the 4, which is cheaper than the 5. From there only 2 and 1 are left, so it pays 1 + 1 + 4 + 2 + 1 = 9. The early cheap step led straight into the 4, and looking one tile ahead could not see that coming.

Trying every walk does find 7. Example 1 has six walks, with sums 7, 11, 12, 9, 10 and 9. But bigger grids have far more walks, so can we find the cheapest one without listing them all?

Think about the last step instead of the first. Every walk ends on the bottom-right tile, in row 2 and column 2 when counting from 0, and it arrives either from the tile above it or from the tile on its left. So the cheapest walk to the corner is the cheaper of two walks, the cheapest one to the tile above and the cheapest one to the tile on the left, plus the corner's own toll of 1. The same reasoning works for every tile, not only the corner.

Left, the grid of Example 1 with the cheapest path 1, 3, 1, 1, 1 highlighted, total 7. Right, the cheapest cost to reach each cell: row 0 is 1, 4, 5; row 1 is 2, 7, 6; row 2 is 6, 8, 7. The bottom-right 7 is 1 plus the smaller of 6 above and 8 on the left.

Look at the picture above. On the left, under "the grid", the cheapest path is highlighted in orange. On the right, under "cheapest cost to reach the cell", each cell holds the cost of the cheapest walk from the top-left corner to that cell. Row 0 reads 1, 4, 5: those tiles can only be reached from the left, so the costs simply add up. Column 0 reads 1, 2, 6 for the same reason, going down.

Every other cell takes its own toll plus the smaller of the two costs above it and to its left. In row 1, column 1, the toll is 5, and the smaller of 4 above and 2 on the left is 2, so the cell holds 7. In the bottom-right corner, the two teal cells offer 6 from above and 8 from the left. The corner holds 1 + 6 = 7, the answer.

So the right-hand grid can be filled in one pass, row by row, because each cell needs only two cells that are already filled. Answering "what is the cheapest walk to this tile?" for every tile, and building each answer from two answers stored earlier, is called dynamic programming.

Solution Approach

Listing every path is slow, and a table of cheapest costs avoids it once three things are settled: what one entry holds, how the first row and column are filled, and how much of the table to keep.

Listing every path

How many paths are there? Every path makes m - 1 moves down and n - 1 moves right, in some order. That gives 6 paths for Example 1, 48,620 for a 10 × 10 grid and 35,345,263,800 for a 20 × 20 grid. Most of those paths share their first steps, so listing them adds the same tolls together again and again.

What one table entry holds

What should the table store? The table is named dp, and its entry dp[i][j] is the cost of the cheapest walk from the top-left cell to the cell in row i and column j, counting the tolls of both ends. That is the right-hand grid in the picture. Since a walk enters a cell from above or from the left, each entry follows one rule.

The rule is dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]).

Filling the rows from top to bottom, and each row from left to right, means both entries on the right-hand side are ready when they are needed. The answer is the last entry, dp[m - 1][n - 1].

The first row and the first column

What about cells with no cell above or no cell to the left? The top-left cell starts every walk, so its entry is its own toll. Cells in row 0 have nothing above them, so they add their toll to the entry on their left. Cells in column 0 have nothing to their left, so they add their toll to the entry above. In Example 1 that gives 1, 4, 5 across the top and 1, 2, 6 down the side.

Keeping one row instead of the whole table

Does the code need the full m × n table? Filling row i reads only row i - 1 and the part of row i already filled, so one array of n entries is enough. Before dp[j] is updated, it still holds the cost to the cell above. Its left neighbour, dp[j - 1], was just updated, so it holds the cost to the cell on the left.

In Example 1, the array holds 1, 4, 5 after row 0. Row 1 then writes 1 + 1 = 2, then 5 + min(4, 2) = 7, then 1 + min(5, 7) = 6, giving 2, 7, 6. Row 2 gives 6, 8, 7, the bottom row of the right-hand grid.

Java Solution

The method minPathSum works in these steps:

  1. First, store the number of rows in m and the number of columns in n, and create the array dp of length n, which holds the cheapest costs for one row at a time.
  2. Visit the cells with two loops, one inside the other. The outer loop moves i down the rows, and the inner loop moves j across the columns of row i.
  3. For each cell, pick one of four cases. The top-left cell sets dp[0] to grid[0][0]. In row 0, the entry is dp[j - 1] + grid[i][j], the cost from the left. In column 0, it is dp[j] + grid[i][j], the cost from above. Everywhere else, it is Math.min(dp[j], dp[j - 1]) + grid[i][j].
  4. After the last row, dp[n - 1] holds the cheapest cost to the bottom-right cell, and the method returns it.

The main method hands each grid to a small helper, run, which prints the grid row by row and then its answer. It tries both examples, a grid with a single column, and a grid of one cell.

Java
import java.util.Arrays;

public class MinimumPathSum {

    public static int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[] dp = new int[n]; // dp[j]: cheapest path cost to (current row, j)
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0) {
                    dp[j] = grid[0][0];                  // start cell
                } else if (i == 0) {
                    dp[j] = dp[j - 1] + grid[i][j];      // first row: only from the left
                } else if (j == 0) {
                    dp[j] = dp[j] + grid[i][j];          // first column: only from above
                } else {
                    dp[j] = Math.min(dp[j], dp[j - 1]) + grid[i][j]; // above or left
                }
            }
        }
        return dp[n - 1];
    }

    static void run(int[][] grid) {
        System.out.println("grid:");
        for (int[] row : grid) {
            System.out.println("  " + Arrays.toString(row));
        }
        System.out.println("minimum path sum = " + minPathSum(grid));
    }

    public static void main(String[] args) {
        run(new int[][] {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}});
        run(new int[][] {{1, 2, 3}, {4, 5, 6}});
        run(new int[][] {{1}, {2}, {3}});
        run(new int[][] {{5}});
    }
}

Running it prints:

Output
grid:
  [1, 3, 1]
  [1, 5, 1]
  [4, 2, 1]
minimum path sum = 7
grid:
  [1, 2, 3]
  [4, 5, 6]
minimum path sum = 12
grid:
  [1]
  [2]
  [3]
minimum path sum = 6
grid:
  [5]
minimum path sum = 5

The first grid gives minimum path sum = 7, the orange path in the picture, and not the 9 of the walk that always steps onto the cheaper next tile. The second grid gives 12, from the path 1 → 2 → 3 → 6 along the top row and down the last column.

The single column [1], [2], [3] has one path, straight down, so every cell after the first takes the column 0 case and the sum is 1 + 2 + 3 = 6. The grid [5] has one cell, which is both start and end, so the top-left case is the whole walk and the answer is 5.

Complexity

The work is one visit to every cell, with the cheapest costs of a single row kept in memory.

  • Time: O(m × n), because the two loops visit each of the m × n cells once, and each visit compares at most two stored costs.
  • Space: O(n), because dp keeps one cheapest cost per column, and each row writes over the costs of the row above.

Counting the paths through the grid, instead of finding the cheapest one, is Unique Paths.