DSA Factory
Free Dynamic programming lessonsDynamic programming · Stage 3 · Grids · Step 2

The cheapest way to the corner

The same two neighbours decide a cell's cost — take whichever is cheaper, then add this cell. About 11 minutes.

Tolls on every block

Same robot, same right-or-down moves, but now every block charges a toll. Instead of counting routes, you want the cheapest one.

That changes one word in the rule. You still arrive from above or from the left, but you'd only ever pick the cheaper of the two. So the cheapest cost to reach a block is its own toll plus the smaller of the two costs next to it. Counting added the two neighbours; choosing takes the smaller one.

Pick the cheaper way in: then pay this block's toll.
Left: the grid. Right: the cheapest cost to reach each cell
012 012
1
3
1
1
1
5
1
4
2
1

The start costs its own number: 1.

Move 1 of 7

The edges still have only one road

Along the top edge and down the left edge there's no choice to make: only one road leads there. So their costs are just running totals of the tolls so far.

Inside the grid, every box has two real options, and the smaller one wins. In the example the cheapest trip costs 7, going right along the top and then down the right side: 1, 3, 1, 1, 1.

No choice on the edges: just add up the tolls along the way.
In code
up = best[r - 1][c]
left = best[r][c - 1]
best[r][c] = grid[r][c] + max(up, left)
Quick check

Reaching the block above costs 9 at best, and reaching the block on the left costs 4. This block's toll is 2. What's the cheapest way to reach it?

  1. A6
  2. B11
  3. C15
Show the answer

6. Come in from the left (4), the cheaper side, and pay the toll of 2: 6.

Your problem

Minimum path sum

You get a grid of non-negative integers. Starting at the top-left corner and moving only right or down, return the smallest possible sum of the numbers along a path to the bottom-right corner.

Example
grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]] → 7

1 ≤ rows, cols ≤ 200 · 0 ≤ grid[i][j] ≤ 1,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve