Leetcode 64.Minimum path Sum (shortest path) ideas and methods for solving problems

Source: Internet
Author: User

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.


Idea: This question is very similar to the previous robot's problem, just a little change, the specific code and comments are as follows:

public class Solution {public    int minpathsum (int[][] grid) {        //Dynamic planning idea        //Select the minimum value to this point (minimum value from top and left) for        ( int i = 0; i < grid.length; i++)            for (int j = 0; J < Grid[0].length; J + +) {                if (i > 0 && J > 0)//Three cases, second row after second column                    Grid[i][j] + = Math.min (grid[i-1][j],grid[i][j-1]);                else if (i = = 0 && J > 0)//First line                    grid[i][j] + = grid[i][j-1];                else if (i > 0 && j==0)//First column                    grid[i][j] + = Grid[i-1][j];            }        Returns the last value return        grid[grid.length-1][grid[0].length-1];}    }


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 64.Minimum path Sum (shortest path) ideas and methods for solving problems

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.