min-path sum --p64--dynamic programming

package DynamicProgramming;

/**
 * Given an mxn grid of non-negative integers, find a path from the upper left corner to the lower right corner such that the sum of the numbers on the path is the smallest.

 Description: You can only move down or to the right one step at a time.

 Example:

 enter:
 [
 [1,3,1],
 [1,5,1],
 [4,2,1]
 ]
 Output: 7
 Explanation: Because the sum of paths 1→3→1→1→1 is the smallest.


 */ 
public  class p64 {
     // To find the shortest distance from the current point to the end point, just find the distance min1 from the right point to the end point, and the distance min2 from the next point to the end point, take the smaller value and + its own value 
    public  int minPathSum( int [][] grid) {
         int MinSumSave[][]= new  int [grid.length+1][grid[0].length+1];             // Used to store the result of previous traversal, longer than grid The lenient 1 is because of the critical problem 
        return MinSum(grid,0,0 ,MinSumSave);
    }

    // dynamic programming solver 
    private  int MinSum( int [][]grid, int i, int j, int MinSumSave[][]){
         if (i>=grid.length) return 9999;              // if it exceeds the range, return the maximum Value 
        if (j>=grid[0].length) return 9999 ;
         if (i==grid.length-1&&j==grid[0].length-1) return grid[i][j];      // to the end , return the end value 
        int min1,min2;
         if (MinSumSave[i+1][j]!=0){           // If it has been calculated before, take the previous operation result 
            min1=MinSumSave[i+1][j];
        }else{
            min1=MinSum(grid,i+1,j,MinSumSave);
            MinSumSave[i+1][j]=min1;
        }
        if (MinSumSave[i][j+1]!=0){           // If it has been calculated before, take the previous operation result 
            min2=MinSumSave[i][j+1 ];
        }else{
            min2=MinSum(grid,i,j+1,MinSumSave);
            MinSumSave[i][j+1]=min2;
        }
        return Math.min(min1,min2)+grid[i][j];
    }

    public static void main(String argv[]){
        p64 temp=new p64();
        int [][]grid={{1,3,1},{1,5,1},{4,2,1}};
        System.out.println(temp.minPathSum(grid));
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325645802&siteId=291194637