<p>Given an <code>n x n</code> integer matrix <code>grid</code>, return <em>the minimum sum of a <strong>falling path with non-zero shifts</strong></em>.</p>

<p>A <strong>falling path with non-zero shifts</strong> is a choice of exactly one element from each row of <code>grid</code> such that no two elements chosen in adjacent rows are in the same column.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/falling-grid.jpg" style="width: 244px; height: 245px;" />
<pre>
<strong>Input:</strong> grid = [[1,2,3],[4,5,6],[7,8,9]]
<strong>Output:</strong> 13
<strong>Explanation:</strong> 
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&nbsp;[1,5,7], so the answer is&nbsp;13.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> grid = [[7]]
<strong>Output:</strong> 7
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == grid.length == grid[i].length</code></li>
	<li><code>1 &lt;= n &lt;= 200</code></li>
	<li><code>-99 &lt;= grid[i][j] &lt;= 99</code></li>
</ul>

class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& grid) {
        int n = grid.size();
        if(n == 1) return grid[0][0];
        
        vector<int> prev(n, 0);
        int ans = INT_MIN;
        int l1, l2;
        for(int i = 0; i < n; i++)
        {
            prev[i] = grid[0][i];
            ans = min(ans, prev[i]);
        }
        if(grid[0][1] < grid[0][0])l1=1, l2=0;
        else l2 = 1, l1 = 0;
        for(int i = 2; i < n; i++)
        {
            if(prev[i] < prev[l1])
            {
                l2 = l1;
                l1 = i;
            }
            else if(prev[i] <= prev[l2])
            {
                l2 = i;
            }
        }
//cout << prev[l1] << " " << prev[l2] << endl;
        for(int i = 1; i < n; i++)
        {
            vector<int> cur(n, 0);
            int ans = INT_MAX;
            for(int j = 0; j < n; j++)
            {
                if(j == l1) cur[j] = prev[l2] + grid[i][j];
                else if(j == l2) cur[j] = prev[l1] + grid[i][j];
                else cur[j] = min(prev[l1], prev[l2]) + grid[i][j];
                ans = min(ans, cur[j]);
                //cout << cur[j] << " ";
            }
           // cout << endl;
            int k2 , k1 ;

            if(cur[1] < cur[0])k1=1, k2=0;
            else k2 = 1, k1 = 0;
            for(int k = 2; k < n; k++)
            {
                if(cur[k] < cur[k1])
                {
                    k2 = k1;
                    k1 = k;
                }
                else if(cur[k] <= cur[k2])
                {
                    k2 = k;
                }
            }

            l1 = k1, l2 = k2;

            prev = cur;
        }

        return prev[l1];
    }
};
18300