2-D Dynamic Programming Paths in a grid
543. Minimum Falling Path Sum
You are given an n × n grid of integers, matrix. A falling path starts at any cell of the top row
and moves down one row at a time until it reaches the bottom row. From the cell in row r and column c,
the next cell is in row r + 1 and in column c − 1, c or c + 1: straight below, or one step to
either side. A path never leaves the grid.
The sum of a falling path is the sum of the values in the cells it visits, one cell in each row. Return the smallest sum of any falling path.
Example 1
Input: matrix = [[6, 1, 4, 8],
[9, 8, 7, 2],
[2, 4, 4, 7],
[3, 4, 7, 3]]
13Explanation: The path takes 4, 2, 4 and 3, stepping down-right, down-left and down-right. Every path that starts at the smallest top cell, 1, sums to at least 14.
Example 2
Input: matrix = [[-4, 7, -1], [2, -9, 6], [-3, 8, -5]]
-18Explanation: The path takes −4, −9 and −5, stepping down-right twice.
Example 3
Input: matrix = [[-7]]
-7Explanation: The grid has one cell, so the only falling path is that cell.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
n == matrix.length == matrix[i].length1 ≤ n ≤ 316-104 ≤ matrix[i][j] ≤ 104
Clarifying questions
What you would ask an interviewer before writing any code.