4.2矩阵的最小路径和

版权声明:本文采用 知识共享署名4.0 国际许可协议进行许可。 https://blog.csdn.net/youmian6868/article/details/85234163
题目

给定一个矩阵m,从左上角开始每次只能向右或者向下走,最后到达右下角的位置,路径上所有的数字累加起来就是路径和,返回所有路径和中最小的路径和。

代码实现
/**
 * 构建大小和m一样的矩阵dp,dp[i][j]的值表示从(0,0)位置走到(i,j)位置的最小路径和。
 *
 * @param m
 * @return 最小的路径和
 */
public int minPathSum1(int[][] m) {
    if (m == null || m.length == 0 || m[0] == null || m[0].length == 0) {
        return 0;
    }

    int row = m.length;
    int col = m[0].length;
    int[][] dp = new int[row][col];
    dp[0][0] = m[0][0];

    for (int i = 1; i < row; i++) {
        dp[i][0] = dp[i - 1][0] + m[i][0];
    }

    for (int j = 1; j < col; j++) {
        dp[0][j] = dp[0][j - 1] + m[0][j];
    }

    for (int i = 1; i < row; i++) {
        for (int j = 1; j < col; j++) {
            dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + m[i][j];
        }
    }

    return dp[row - 1][col - 1];
}

/**
 * 压缩辅助空间,仅仅使用大小为min{M,N}的arr数组
 *
 * 这种方法不能取得具体路径
 *
 * @param m
 * @return 最小的路径和
 */
public int minPathSum2(int[][] m) {
    if (m == null || m.length == 0 || m[0] == null || m[0].length == 0) {
        return 0;
    }

    int more = Math.max(m.length, m[0].length);
    int less = Math.min(m.length, m[0].length);
    boolean rowmore = more == m.length; //行数是否大于等于列数
    int[] arr = new int[less]; //辅助数组的长度为行数与列数中的最小值
    arr[0] = m[0][0];

    for (int i = 1; i < less; i++) {
        arr[i] = arr[i - 1] + (rowmore ? m[0][i] : m[i][0]);
    }

    for (int i = 1; i < more; i++) {
        arr[0] = arr[0] + (rowmore ? m[i][0] : m[0][i]);
        for (int j = 1; j < less; j++) {
            arr[j] = Math.min(arr[j - 1], arr[j]) + (rowmore ? m[i][j] : m[j][i]);
        }
    }

    return arr[less - 1];
}

猜你喜欢

转载自blog.csdn.net/youmian6868/article/details/85234163