---
# System prepended metadata

title: 1289. Minimum Falling Path Sum II

---

# 1289. Minimum Falling Path Sum II

## Description
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.

## Example 

### Example1
![image](https://hackmd.io/_uploads/HyX71j_-A.png)

>Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
Explanation: 
The possible falling paths are:
[1,5,9], [1,5,7], [1,6,7], [1,6,8],
[2,4,8], [2,4,9], [2,6,7], [2,6,8],
[3,4,8], [3,4,9], [3,5,7], [3,5,9]
The falling path with the smallest sum is [1,5,7], so the answer is 13.

### Example 2:

>Input: grid = [[7]]
Output: 7

## Constraints:

* `n == grid.length == grid[i].length`
* `1 <= n <= 200`
* `-99 <= grid[i][j] <= 99`

## 思路

使用 DP 將每一層最小的值加進下一層之中，因為他限制不能使用上下相鄰的用素，所以要多加判斷，不能直接取最小值。
所以如 example:
[[1,2.3],
[4,5,6],
[7,8,9]]
first iteration
[[1,2.3],
[6,6,7],
[7,8,9]]
second iteration
[[1,2.3],
[6,6,7],
[13,14,15]]
我們再取最後一層獲取最小的元素 ans = 13

會使用一個 tmp vector 去暫存前一層數據，將他 sort 之後可以選到最小值或是第二小值。
這邊要筆記的是 c++ vector 的複製是使用 `tmp = grid[i - 1]`，直接對應要複製的值就可以完成複製。

## C++
```cpp
class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& grid) {
        int n = grid.size();
        int i, j;
        vector<int> tmp(n);

        for (i = 1; i < n; i++) {
            tmp = grid[i - 1];
            sort(tmp.begin(), tmp.end());
            for (j = 0; j < n; j++) {
                if (grid[i - 1][j] == tmp[0])
                    grid[i][j] += tmp[1];
                else
                    grid[i][j] += tmp[0];
            }
        }
        return *min_element(grid[n - 1].begin(), grid[n - 1].end());
    }
};
```
