Minimum Falling Path Sum II

Given an n x n matrix, return the minimum sum of a falling path where you may move to any column in the next row except the same column. Pattern focus: Direction variants. Track the smallest and second smallest values in each row to optimize the transition.

Input Format

matrix is an n x n matrix

Output Format

minimum falling path sum with column restriction

Constraints

  • 1 <= n <= 200

Examples

Example 1:

Input:

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

Output:

13

Explanation:

The best path avoids reusing the same column and totals 13.

Example 2:

Input:

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

Output:

12

Explanation:

The best valid path totals 12.

Example 3:

Input:

matrix = [[7]]

Output:

7

Explanation:

A one-cell matrix returns 7.

Loading...
Minimum Falling Path Sum II - Dp Grid