[Niuke.com-High-frequency Interview Questions for Famous Enterprises] The minimum path sum of NC59 matrix-dynamic programming

Minimum path of the matrix

Title description

Given a matrix a of n * m, starting from the upper left corner, you can only go to the right or down at a time, and finally reach the lower right corner. The sum of all the numbers on the path is the path sum, and the smallest of all paths is output. Path and.

Example 1
input

[[1,3,5,9],[8,1,3,4],[5,0,6,1],[8,8,4,0]]

return value

12

Problem-solving ideas

The first row can only go from left to right
. The value of the first element is the first element of the original array dp[0][0] = a[0][0] dp[0][j] = a[0][j] + dp[0][j-1];

The first column of elements can only be from top to bottom dp[i][0] = dp[i-1][0] + a[i][0]

The elements in the second row and second column may come from the left node and the upper node of the current node

Then the minimum value of the node should be the value of the current node plus min (the left node of the upper node) dp[i][j] = a[i][j] + Math.min(dp[i][j-1],dp[i-1][j]);

Then the value of the last node is the smallest path and

import java.util.*;


public class Solution {
    
    
    /**
     * 
     * @param matrix int整型二维数组 the matrix
     * @return int整型
     */
    public int minPathSum (int[][] matrix) {
    
    
        // write code here
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] dp = new int[m][n];
        dp[0][0] = matrix[0][0];
        //第一行
        for(int i = 1;i < n;i++){
    
    
            dp[0][i] = dp[0][i - 1] + matrix[0][i];
        }
        //第一列
        for(int i = 1;i < m;i++){
    
    
            dp[i][0] = dp[i - 1][0] + matrix[i][0];
        }
        for(int i = 1;i < m;i++){
    
    
            for(int j = 1;j < n;j++){
    
    
                dp[i][j] = Math.min(dp[i][j- 1],dp[i - 1][j]) + matrix[i][j];
            }
        }
        return dp[m-1][n-1];
    }
}

Guess you like

Origin blog.csdn.net/qq_35655602/article/details/115057379