Problem
Given an n x n
integer matrix grid
, return the minimum sum of a falling path with non-zero shifts.
A falling path with non-zero shifts is a choice of exactly one element from each row of grid
such that no two elements chosen in adjacent rows are in the same column.
Examples
Example 1
|
|
Example 2
|
|
Constraints
n == grid.length == grid[i].length
1 <= n <= 200
-99 <= grid[i][j] <= 99
Solution
Method 1 – Dynamic Programming with Min Tracking
Intuition
To avoid picking the same column in adjacent rows, for each cell, we add the minimum value from the previous row except the same column. To optimize, we track the smallest and second smallest values in the previous row and their column indices.
Approach
- For each row, keep track of the minimum and second minimum values and their column indices from the previous row.
- For each cell in the current row:
- If its column is not the same as the minimum column from the previous row, add the minimum value.
- Otherwise, add the second minimum value.
- Update the minimums for the current row.
- The answer is the minimum value in the last row.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
— For each cell, we scan all columns in each row. - 🧺 Space complexity:
O(n)
— For the DP array.