oneby7

2-D Dynamic Programming Paths in a grid

541. Minimum Path Sum

Medium

You are given a grid of non-negative integers, grid, with m rows and n columns. A path starts in the top-left cell and ends in the bottom-right cell. Each step moves one cell down or one cell to the right. It cannot move up, left or diagonally.

The sum of a path is the total of the values in every cell it visits, the first and the last cell included. Return the smallest sum of any such path.

Example 1

329658171142

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

Output: 16

Explanation: The path goes down twice and then right three times, through 3, 5, 1, 1, 4 and 2, for a sum of 16. A path that starts with the cheaper step to the 2 must then pay the 8 or the 9, and costs at least 20.

Example 2

600090800

Input: grid = [[6, 0, 0], [0, 9, 0], [8, 0, 0]]

Output: 6

Explanation: Every path pays the 6 in the top-left cell. The path right, right, down, down adds only zeros after it.

Example 3

40729

Input: grid = [[4, 0, 7, 2, 9]]

Output: 22

Explanation: The grid is a single row, so the only path visits every cell.

Check your understanding

Work out the answer for this input before you write any code.

grid = [[4, 1, 6], [2, 9, 1], [3, 2, 5]]

Constraints

  • m == grid.length, n == grid[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105
  • 0 ≤ grid[i][j] ≤ 104

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.