CodingNodes / 2-D Dynamic Programming / Minimum Path Sum System design Space play · ←→ step · R restart

Problem

You are given a grid of non-negative numbers. Start at the top-left cell and walk to the bottom-right cell, moving only right or down. Every cell you stand on, including the first and the last, adds its number to your total.

Return the smallest total any such walk can have.

Constraints

  • 1 ≤ rows, columns ≤ 200
  • 0 ≤ grid[r][c] ≤ 200

Examples: pick one to animate

Solutions

TimeO(m·n) SpaceO(m·n)

Time: Each of the m·n cells is filled once with one comparison and one addition.

Space: The dp table has the same shape as the grid.

dp[r][c] is the cheapest total to reach cell (r, c). You arrive from above or from the left, so dp[r][c] = min(dp[r-1][c], dp[r][c-1]) + grid[r][c]. The top row and left column have only one way in, so they are plain running sums.