2-D Dynamic Programming Paths in a grid
541. Minimum Path Sum
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
Input: grid = [[3, 2, 9, 6], [5, 8, 1, 7], [1, 1, 4, 2]]
16Explanation: 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
Input: grid = [[6, 0, 0], [0, 9, 0], [8, 0, 0]]
6Explanation: Every path pays the 6 in the top-left cell. The path right, right, down, down adds only zeros after it.
Example 3
Input: grid = [[4, 0, 7, 2, 9]]
22Explanation: 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.
Constraints
m == grid.length,n == grid[i].length1 ≤ m, n ≤ 1051 ≤ m · n ≤ 1050 ≤ grid[i][j] ≤ 104
Clarifying questions
What you would ask an interviewer before writing any code.