« Back
in Array Dynamic Programming read.

Leetcode 64 Minimum Path Sum.

Problem 64 Minimum Path Sum

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 Problem 62

Nothing to say just be careful with the upper limit of the array when using a recursion.

public class Solution {
    public int minPathSum(int[][] grid) {
        int rownum=grid.length;
        int colnum=grid[0].length;

        if(rownum==1&&colnum==1){
            return grid[0][0];
        }

        int[][] minPath=new int[rownum][colnum];
        minPath[0][0]=grid[0][0];

        for(int i=1;i < rownum;i++){
            minPath[i][0]=minPath[i-1][0]+grid[i][0];
        }

        for(int i=1;i < colnum;i++){
            minPath[0][i]=minPath[0][i-1]+grid[0][i];
        }


        for(int i=1;i < rownum;i++){
            for(int j=1;j < colnum;j++){
                minPath[i][j]=Math.min(grid[i][j]+minPath[i-1][j], grid[i][j]+minPath[i][j-1]);
            }
        }
        return minPath[rownum-1][colnum-1];
    }
}
comments powered by Disqus