1289. 下降路径最小和 II 23.12.22(一)

给你一个 n x n 整数矩阵 grid ,请你返回 非零偏移下降路径 数字和的最小值。

非零偏移下降路径 定义为:从 grid 数组中的每一行选择一个数字,且按顺序选出来的数字中,相邻数字不在原数组的同一列。

示例 1:

输入:grid = [[1,2,3],[4,5,6],[7,8,9]]
输出:13
解释:
所有非零偏移下降路径包括:
[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]
下降路径中数字和最小的是 [1,5,7] ,所以答案是 13 。
示例 2:

输入:grid = [[7]]
输出:7
 

提示:

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

public class Solution {
    public int MinFallingPathSum(int[][] grid) {
        int m = grid.Length,n=grid[0].Length;
        int[,] dp = new int[m,n];
        for (int i = 0; i < n; i++) dp[0,i] = grid[0][i];
        for (int i = 1; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dp[i,j] = int.MaxValue;;
                int val = grid[i][j];
                for (int p = 0; p < n; p++) {
                    if (j != p) {
                        dp[i,j] = Math.Min(dp[i,j], dp[i-1,p] + val);
                    }
                }
            }
        }
        int ans = int.MaxValue;;
        for (int i = 0; i < n; i++) {
            ans = Math.Min(ans, dp[m-1,i]);
        }
        return ans;
    }
}
public class Solution {
    int MAX = int.MaxValue;
    public int MinFallingPathSum(int[][] grid) {
        int m = grid.Length,n=grid[0].Length;
        int[,] dp = new int[m,n];
        int i1 = -1,i2 = -1;
        for (int i = 0; i < n; i++){
            int val = grid[0][i];
            dp[0,i] = val;
            if(val<(i1 == -1?MAX:dp[0,i1])){
                i2 = i1;
                i1 = i;
            }
            else if(val<(i2 == -1?MAX:grid[0][i2])){
                i2 = i;
            }
        }
        for (int i = 1; i < m; i++) {
            int t1=-1,t2=-1;
            for (int j = 0; j < n; j++) {
                dp[i,j] = MAX;
                int val = grid[i][j];
                if(j!=i1) dp[i,j] = dp[i-1,i1] + val;
                else dp[i,j] = dp[i-1,i2] + val;
                if(dp[i,j]<(t1 == -1?MAX:dp[i,t1])){
                    t2 = t1;
                    t1 = j;
                }
                else if(dp[i,j]<(t2 == -1?MAX:dp[i,t2])) t2 = j;
            }
            i1 = t1;
            i2 = t2;
        }
        int ans = int.MaxValue;;
        for (int i = 0; i < n; i++) {
            ans = Math.Min(ans, dp[m-1,i]);
        }
        return ans;
    }
}

你可能感兴趣的:(一天二算法(LeetCode),算法,数据结构,leetcode)