LeeCode64 minimum path and (Java) (dp)

Topic link: LeeCode64 minimum path and
topic description: The Insert picture description here
minimum cost when using dp array to record to the current grid. Each time a small value is taken from the top grid and the left grid and added to the current grid is the minimum cost of the current grid.

public static int minPathSum(int[][] grid) {
    
    
        int[][] dp=new int[grid.length][grid[0].length];
        dp[0][0]=grid[0][0];
        for (int i = 1; i < grid[0].length; i++) {
    
    
            dp[0][i]=dp[0][i-1]+grid[0][i];
        }
        for (int i = 1; i < grid.length; i++) {
    
    
            dp[i][0]=dp[i-1][0]+grid[i][0];
        }
        for (int i = 1; i < grid.length; i++) {
    
    
            for (int j = 1; j < grid[0].length; j++) {
    
    
                dp[i][j]= Math.min(dp[i][j-1]+grid[i][j],dp[i-1][j]+grid[i][j]);
            }
        }
        /*for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                System.out.print(dp[i][j]+"\t");
            }
            System.out.println();
        }*/
        return dp[grid.length-1][grid[0].length-1];
    }

Guess you like

Origin blog.csdn.net/weixin_43590593/article/details/112747936