MediumArrayDynamic ProgrammingMatrix

1 approach, code in every language

Problem description

You are given an m x n grid filled with non-negative numbers. Starting from the top-left cell you want to reach the bottom-right cell, and on each move you may travel only one cell to the right or one cell down.

Return the smallest possible sum of all numbers along a valid path from the top-left corner to the bottom-right corner.

Example 1

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]

Output: 7

The route 1 -> 3 -> 1 -> 1 -> 1 accumulates the minimum total of 7.

Example 2

Input: grid = [[1,2,3],[4,5,6]]

Output: 12

The path 1 -> 2 -> 3 -> 6 sums to 12, the least achievable for this grid.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 200

After the pattern

Now solve one you haven't seen.

Cheapest Bay Route is our own problem on the technique behind Minimum Path Sum: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free