"Array" Minimum Path Sum

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.

Ideas:

RES[I][J] represents the smallest path and from the upper-left corner to Grid[i][j]. Then res[i][j] = grid[i][j] + min (res[i-1][j], res[i][j-1]);

In the following code, in order to deal with the boundary conditions of the first and first columns, we make res[i][j] represent the smallest path from the upper left to the grid[i-1][j-1] and the last rs[m][n] is the result of our request.

/** * @param {number[][]} grid * @return {number}*/varMinpathsum =function(grid) {varm=Grid.length,n; if(m==0){        return0; }Else{n=grid[0].length; }        varres=[];  for(vari=0;i<m;i++){         for(varj=0;j<n;j++) {Res[i]=[]; }    }         for(vari=0;i<m;i++){         for(varj=0;j<n;j++){            if(i==0&&j==0) res[0][0]=grid[0][0]; Else if(j==0) res[i][0]=res[i-1][0]+grid[i][0]; Else if(i==0) res[0][j]=res[0][j-1]+grid[0][j]; ElseRes[i][j]=math.min (Res[i-1][j],res[i][j-1]) +Grid[i][j]; }    }        returnRes[m-1][n-1];};

"Array" Minimum Path Sum

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.