Leecode64 minimum-path-sum

Title description

Given a two-dimensional array of mxn filled with non-negative integers, now to walk from the upper left corner to the lower right corner of the two-dimensional array, please find the path with the smallest sum of all the numbers on the path.
Note: You can only move down or right at a time.

analysis

  • The title is similar to Leecode62 unique-paths

java code

public class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;        
        int dp [][] = new int [m][n];
        //到第(0,0)位置路径长度就是元素(0,0)
        dp[0][0] = grid[0][0];
        //初始化第0列时,路径只能从同一列的上一行过来,因此加本位置的数字。     
        for(int i = 1; i < dp.length; i++){            
            dp[i][0] = dp[i-1][0] + grid[i][0];            
        }
         //初始化第0行时,路径只能从同一行的上一列过来,因此加本位置的数字。     
        for(int j = 1; j < dp[0].length;j++){           
            dp[0][j] = dp[0][j-1] + grid[0][j];
        }        
        for(int i = 1; i < dp.length;i++){
           for(int j = 1; j <dp[0].length;j++){
               //某一点只能从上方或者左边过来。
               dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1])+grid[i][j];        
           } 
        }        
        return dp[m-1][n-1];       
    }
}
Published 72 original articles · praised 0 · visits 731

Guess you like

Origin blog.csdn.net/weixin_40300702/article/details/105403065