KatInterview

Cheapest Right-Down Route Through a Cost Grid

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

Last updated

Compute the minimum total cost of a route from the top-left to the bottom-right of a grid when only right and down moves are allowed, using dynamic programming.

Cheapest Right-Down Route

You are given a rectangular grid with m rows and n columns. Every cell holds a non-negative integer, which is the cost of stepping on that cell.

A route begins at the top-left cell (0, 0) and ends at the bottom-right cell (m-1, n-1). From any cell you may move exactly one step right or exactly one step down; no other moves are permitted. The cost of a route is the sum of the values of every cell it visits, including both the starting cell and the final cell.

Return the smallest possible cost over all valid routes.

For instance, in the grid [[1, 3, 1], [1, 5, 1], [4, 2, 1]] the cheapest route visits cells with values 1, 3, 1, 1, 1, so the answer is 7.

Input

  • grid: a list of m lists, each containing n non-negative integers.

Output

  • A single integer: the minimum route cost.

Notes

  • A grid with a single cell has exactly one route, whose cost is that cell's value.
  • In a grid with one row or one column, the route is forced.

Constraints

  • 1 <= m, n <= 200
  • The grid is non-empty and rectangular (all rows have the same length).
  • Every cell value is a non-negative integer.

Examples

Example 1

Input: cheapest_route_cost([[1, 3, 1], [1, 5, 1], [4, 2, 1]])

Output: 7

Hints

Hint 1

Think about the last step of any route: the final cell is entered either from the cell above it or from the cell to its left. What does that say about the best cost of reaching it?

Hint 2

Define best[r][c] as the cheapest cost to arrive at cell (r, c). Then best[r][c] = grid[r][c] + min(best[r-1][c], best[r][c-1]), with only one available predecessor along the first row and first column.

Hint 3

Cells are processed row by row, so you only need the previous row's values. A single array of length n, updated in place as you sweep each row, is enough.