Cheapest Right-and-Down Route Across a Cost Map
Dynamic ProgrammingAuto-graded · 19 test casesLast updated
Compute the minimum total cost of a route through a rectangular cost grid using only right and down moves, which tests 2D dynamic programming with a space optimization.
Cheapest Right-and-Down Route Across a Cost Map
A delivery drone flies over a rectangular map divided into square zones. Each zone has a non-negative integer toll. The map is given as a 2D list grid with m rows and n columns, where grid[i][j] is the toll for the zone in row i and column j.
The drone starts in the top-left zone (0, 0) and must reach the bottom-right zone (m-1, n-1). From any zone it may move one step right or one step down. Moving left, up, or diagonally is not allowed.
The cost of a route is the sum of the tolls of every zone it visits, including the starting zone and the final zone.
Write a function that returns the smallest possible total cost over all valid routes.
Notes
- If the grid has only one row or only one column, there is exactly one route, and its cost is the sum of all the tolls.
- A
1 x 1grid has a cost equal to its single value. - Tolls may be
0.
Input
grid: a list ofmlists, each of lengthn, containing non-negative integers.
Output
- An integer: the minimum total toll of a route from the top-left zone to the bottom-right zone.
Constraints
1 <= m, n <= 2000 <= grid[i][j] <= 100- Every row of
gridhas the same length.
Examples
Example 1
Input: cheapest_route_cost([[1, 3, 1], [1, 5, 1], [4, 2, 1]])
Output: 7
Example 2
Input: cheapest_route_cost([[1, 2, 3], [4, 5, 6]])
Output: 12
Example 3
Input: cheapest_route_cost([[5]])
Output: 5
Hints
Hint 1
Any route enters a zone either from the zone directly above it or from the zone directly to its left. What does that tell you about the cheapest cost of reaching that zone?
Hint 2
Define best[i][j] as the cheapest cost to reach zone (i, j). Then best[i][j] = grid[i][j] + min(best[i-1][j], best[i][j-1]). The first row and first column each have only one possible predecessor.
Hint 3
Row i depends only on row i-1 and on cells already computed in row i, so a single array of length n, updated left to right, is enough.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because the drone can only move right or down, the last step into zone (i, j) must come from (i-1, j) or from (i, j-1). The cheapest route to (i, j) is therefore the zone's own toll plus the cheaper of the best routes to those two neighbors:
best(i, j) = grid[i][j] + min(best(i-1, j), best(i, j-1))
The boundaries are special cases:
- First row: a zone can only be entered from its left, so
bestis a running prefix sum. - First column: a zone can only be entered from above, so
bestis also a running prefix sum. - Start zone:
best(0, 0) = grid[0][0].
The answer is best(m-1, n-1).
Saving space
Row i needs only row i-1 and the cells already computed in row i. A single array best of length n is enough:
- Before
best[j]is updated, it still holds the value for the zone above. best[j-1]has already been updated for this row, so it holds the value for the zone to the left.
So the update is best[j] = min(best[j], best[j-1]) + grid[i][j].
Why it is correct
- Optimal substructure: every route to
(i, j)passes through exactly one of its two allowed predecessors. The cheapest route to(i, j)must extend a cheapest route to one of them, and we take the smaller option. - Valid order: processing rows top to bottom and columns left to right means both predecessors are final before they are used.
- Edge cases: a single row skips the outer loop and gives the row sum. A single column skips the inner loop, and
best[0]accumulates the column sum. A1 x 1grid returns its only value. Zero tolls need no special handling.
Complexity
- Time: O(m · n), since each zone is processed once.
- Space: O(n) for the rolling array.
Reference solution
from typing import List
def cheapest_route_cost(grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
best = [0] * cols
best[0] = grid[0][0]
for j in range(1, cols):
best[j] = best[j - 1] + grid[0][j]
for i in range(1, rows):
best[0] += grid[i][0]
for j in range(1, cols):
best[j] = min(best[j], best[j - 1]) + grid[i][j]
return best[-1]