矩阵最小路径和

public class Main {

    private static int function(int[][] x) {
        if (x == null || x.length == 0 || x[0].length == 0) {
            return 0;
        }
        int[] tmp = new int[x[0].length];

        tmp[0] = x[0][0];
        for (int i = 1;i < x[0].length; ++ i) {
            tmp[i] = tmp[i - 1] + x[0][i];
        }

        for (int i = 1;i < x.length;++ i) {
            tmp[0] += x[i][0];
            for (int j = 1;j < x[0].length;++ j) {
                tmp[j] = Math.min(tmp[j - 1], tmp[j]) + x[i][j];
            }
        }

        return tmp[x[0].length - 1];

    }

    public static void main(String[] args) {
        int[][] x = {{1, 3, 5, 9}, {8, 1, 3, 4}, {5, 0, 6, 1}, {8, 8, 4, 0}};
        System.out.println(function(x));
    }
}


猜你喜欢

转载自blog.51cto.com/tianyiya/2340413