oneby7

2-D Dynamic Programming Paths in a grid

543. Minimum Falling Path Sum

Medium

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

6148987224473473

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

Output: 13

Explanation: 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

-47-12-96-38-5

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

Output: -18

Explanation: The path takes −4, −9 and −5, stepping down-right twice.

Example 3

-7

Input: matrix = [[-7]]

Output: -7

Explanation: 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.

matrix = [[8, 2, 1], [1, 6, 4], [9, 2, 8]]

Constraints

  • n == matrix.length == matrix[i].length
  • 1 ≤ n ≤ 316
  • -104 ≤ matrix[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.