Minimum path sum
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Minimum path sum finds the cheapest route across a grid of costs, moving only right or down. Each square remembers the cheapest way to reach it, using the cheaper of the square above and to the left. It is the basis of cost-based route finding.
Practical use cases
- Web app: Delivery cost map. A courier app lays out a city as a grid where each block has a toll or traffic cost. The planner finds the cheapest route from the depot to the customer by writing the cheapest known cost in every square. The rider's app shows one route and its total cost. When tolls or traffic change, the planner just refills the table, and the rider always gets the cheapest route for today.
- Web app: Farm or field planning tool. An agri-tech dashboard shows a field as a grid with the effort needed to cross each square. The tool works out the least-effort path for a tractor or drone. Farmers can compare the cheapest route with a straight line and see how much effort they save, which helps them plan fuel and time.
- System: GPS cost maps and seam carving. Image tools that resize photos without squashing important parts find a low-cost path of pixels from top to bottom. That is a minimum path through an energy grid. In each of these, every square stores the least cost to be there, and the final corner holds the cheapest total, found without trying every route one by one.
The story: The Toll-Road Tiffin Run
Bunty's tiffin business had grown, and the town had grown too. Every crossing now had a small toll. The tolls at the crossings went like 1, 3, 1, 2 along the top road, and the numbers changed from block to block. Bunty still moved only right or down, but now he asked: "Not how many routes, but which one is the cheapest?"
Mira smiled: "It is the same table as last time, but the questions change. A crossing's best cost is its own toll plus the cheaper way of arriving: from above or from the left." Along the top road there is only one way in (from the left), and along the left road only one way (from above).
They filled the table row by row. The corner at the end held the cheapest total. To see the actual route Bunty walked backwards from the corner: at each box, he stepped to whichever neighbour (above or left) had the smaller total. This simple walk-back is a trick you can use in any DP table.
This is the minimum path sum problem: a grid DP where a cell holds the cheapest cost to reach it. Replace "plus" with "min" and a counting grid becomes a cheapest-route grid.
How to spot this problem, and where you need it
You have a grid where each square has a cost and you need the cheapest way from one corner to the other with limited moves.
Signs you need it
- The problem asks for "minimum cost", "least effort" or "cheapest" path in a grid, with moves right and down only.
- Picking the cheaper neighbour at every step sometimes leads into expensive squares later.
- The grid is big enough that trying all routes is impossible.
Where to use it in a project
- Cost-based route planning in delivery, logistics or farm dashboards.
- Image resizing and any feature that needs a cheapest line through a grid of weights.
The solution
Create a table the same size as the grid. In the top-left cell, store its own cost. In the first row and column, add costs along the edge. For every other cell, store its own cost plus the smaller of the table value above and the table value to the left. The bottom-right cell then holds the cheapest total. To see the path, walk back from there, always stepping to the smaller neighbour.
Payoff: Before: checking every route, billions on a 20-by-20 map. After: 400 cell updates and one cheapest route.
Explain it like I am 8
Every square on a board has a price tag. You want to walk from corner to corner paying as little as possible. At each square you write "the least I could have paid to be here". Because you can only come from above or from the left, you take the cheaper of those two and add this square's price.
How it works, step by step
- State:
dp[r][c]= the cheapest total cost to reach cell(r, c), including its own toll. - Base case:
dp[0][0] = grid[0][0]. - First row and column: only one way in, so add the toll to the previous box.
- Transition:
dp[r][c] = grid[r][c] + min(dp[r-1][c], dp[r][c-1]). - Answer: the bottom-right box. To get the route, walk back from there, each time moving to the cheaper of above or left.
The code in four languages
PHP
<?php
// Cheapest total from top-left to bottom-right, moving only right or down.
function minPathSum(array $g): int {
$rows = count($g);
$cols = count($g[0]);
$dp = array_fill(0, $rows, array_fill(0, $cols, 0));
for ($r = 0; $r < $rows; $r++) {
for ($c = 0; $c < $cols; $c++) {
if ($r === 0 && $c === 0) $dp[$r][$c] = $g[$r][$c]; // base case
elseif ($r === 0) $dp[$r][$c] = $dp[$r][$c - 1] + $g[$r][$c]; // only from the left
elseif ($c === 0) $dp[$r][$c] = $dp[$r - 1][$c] + $g[$r][$c]; // only from above
else $dp[$r][$c] = $g[$r][$c] + min($dp[$r - 1][$c], $dp[$r][$c - 1]);
}
}
return $dp[$rows - 1][$cols - 1];
}
$tolls = [[1, 3, 1, 2], [1, 5, 1, 4], [4, 2, 1, 1]];
echo minPathSum($tolls), "\n"; // 8JavaScript
// Cheapest total from top-left to bottom-right, moving only right or down.
function minPathSum(g) {
const rows = g.length, cols = g[0].length;
const dp = Array.from({ length: rows }, () => new Array(cols).fill(0));
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (r === 0 && c === 0) dp[r][c] = g[r][c]; // base case
else if (r === 0) dp[r][c] = dp[r][c - 1] + g[r][c]; // only from the left
else if (c === 0) dp[r][c] = dp[r - 1][c] + g[r][c]; // only from above
else dp[r][c] = g[r][c] + Math.min(dp[r - 1][c], dp[r][c - 1]);
}
}
return dp[rows - 1][cols - 1];
}
const tolls = [[1, 3, 1, 2], [1, 5, 1, 4], [4, 2, 1, 1]];
console.log(minPathSum(tolls)); // 8Java
public class Main {
// Cheapest total from top-left to bottom-right, moving only right or down.
static int minPathSum(int[][] g) {
int rows = g.length;
int cols = g[0].length;
int[][] dp = new int[rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (r == 0 && c == 0) dp[r][c] = g[r][c]; // base case
else if (r == 0) dp[r][c] = dp[r][c - 1] + g[r][c]; // only from the left
else if (c == 0) dp[r][c] = dp[r - 1][c] + g[r][c]; // only from above
else dp[r][c] = g[r][c] + Math.min(dp[r - 1][c], dp[r][c - 1]);
}
}
return dp[rows - 1][cols - 1];
}
public static void main(String[] args) {
int[][] tolls = {{1, 3, 1, 2}, {1, 5, 1, 4}, {4, 2, 1, 1}};
System.out.println(minPathSum(tolls)); // 8
}
}Go
package main
import "fmt"
// Cheapest total from top-left to bottom-right, moving only right or down.
func minPathSum(g [][]int) int {
rows := len(g)
cols := len(g[0])
dp := make([][]int, rows)
for r := range dp {
dp[r] = make([]int, cols)
}
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
switch {
case r == 0 && c == 0:
dp[r][c] = g[r][c] // base case
case r == 0:
dp[r][c] = dp[r][c-1] + g[r][c] // only from the left
case c == 0:
dp[r][c] = dp[r-1][c] + g[r][c] // only from above
default:
dp[r][c] = g[r][c] + min(dp[r-1][c], dp[r][c-1])
}
}
}
return dp[rows-1][cols-1]
}
func main() {
tolls := [][]int{{1, 3, 1, 2}, {1, 5, 1, 4}, {4, 2, 1, 1}}
fmt.Println(minPathSum(tolls)) // 8
}Time: O(rows × cols) · Extra space: O(rows × cols). Every cell is looked at once. Keeping only the previous row of costs would reduce memory to one row.
Watch out for
- Using the greedy rule "always step to the cheaper neighbour ahead". A cheap next step can lead to an expensive later one; DP looks at totals.
- Forgetting the toll of the starting cell, or counting it twice.
- Treating the first row and column like inner cells, which reads outside the grid.
Quick check
- What does the transition combine for an inner cell?
- Its own toll + the cheaper of above/left totals
- Its own toll + both totals
- Its own toll only
- What is the difference between this and counting grid paths?
- A different board
- "min with a toll" instead of "add the counts"
- Moves are different
- How can you recover the actual cheapest route?
- It cannot be recovered
- Rerun the algorithm with random numbers
- Walk back from the last cell, stepping to the cheaper of above or left