Leetcode: Minimum path sum

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.

Similar to the unique path problem, it is a DP problem. The solution is to build a new matrix, and each element value is the shortest distance from top left to the point. Recursion can be written based on this, and once the shortest distance to this point is calculated, it is saved for use by other points.

 1 public class Solution { 2     public int minPathSum(int[][] grid) { 3         int m = grid.length; 4         int n = grid[0].length; 5         if (m == 0 || n == 0) return 0; 6         int[][] matrix = new int[m][n]; 7         return FindMinPath(m-1, n-1, grid, matrix); 8     } 9     10     public int FindMinPath(int i, int j, int[][]grid, int[][]matrix) {11         if (matrix[i][j] != 0) return matrix[i][j];12         if (i == 0 && j == 0) {13             matrix[i][j] = grid[0][0];14             return matrix[i][j];15         }16         if (i == 0 && j != 0) {17             matrix[i][j] = FindMinPath(i, j-1, grid, matrix) + grid[i][j];18             return matrix[i][j];19         }20         if (i != 0 && j == 0) {21             matrix[i][j] = FindMinPath(i-1, j, grid, matrix) + grid[i][j];22             return matrix[i][j];23         }24         else {25             matrix[i][j] = Math.min(FindMinPath(i, j-1, grid, matrix), FindMinPath(i-1, j, grid, matrix)) + grid[i][j];26             return matrix[i][j];27         }28     }29 }

 

Leetcode: 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.