KatInterview

Cheapest Right-and-Down Route Across a Cost Map

Dynamic ProgrammingAuto-graded · 19 test cases
MediumAuto-gradedDynamic Programmingdynamic-programminggridmatrix

Last 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 1 grid has a cost equal to its single value.
  • Tolls may be 0.

Input

  • grid: a list of m lists, each of length n, 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 <= 200
  • 0 <= grid[i][j] <= 100
  • Every row of grid has 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.