Leetcode 64. Minimum Path Sum Java

Source: Internet
Author: User

Topic:

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes The sum of all numbers along its path.

Note:you can only move either down or right at any point in time.

test instructions and analysis: give a m*n large grid, each of the numbers in the grid is non-negative, each time you can move to the right or down one grid, find the upper left corner of the lattice to the bottom right corner of the grid and the smallest path. I use the solution of dynamic programming, for one point Grid[i][j] (i<i<m.i<j<n), because there are only two ways to reach that point, so the shortest path to this can only be the last point or the left side of the short-circuit strength plus the value of the current point, that is, D (grid I [j]) =min{d (Grid[i][j-1]), D (Grid[i-1][j])} + grid[i][j]. There is only one case for the first row or column to reach that point, so you need to add the current point value directly from the shortest path of the previous point. The final value can be obtained by traversing the entire grid.

Code:

public class Solution {public int minpathsum (int[][] grid) {        int m=grid.length;//row        int n=-1;//column        if (m!=0)        n=grid[0].length;                        Int[][] A=new int[m][n];        for (int i=0;i<m;i++) {for        (int j=0;j<n;j++) {        if (i==0| | j==0) {        if (i==0&&j!=0) {        a[i][j]=a[i][j-1]+grid[i][j];//the value of the first row equals the previous value plus the current value        }else if (i!=0& &j==0) {        a[i][j]=a[i-1][j]+grid[i][j];//the value of the first column equals the value of the current grid        }else {        a[i][j]=grid[i][j];//start point, Is the value of the starting point itself}        }else{        a[i][j]=math.min (a[i][j-1]+grid[i][j],a[i-1][j]+grid[i][j])        ;        }} return a[m-1][n-1];}    }

  

  

Leetcode 64. Minimum Path Sum Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.