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.

Example:
Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
 
 class Solution {
    public int minPathSum(int[][] grid) {
        
        int i, j;
        for(i=0;i<grid.length;i++){
            for(j=0;j<grid[i].length;j++){
                if(i==0 && j>0){
                    grid[i][j] = grid[i][j] + grid[i][j-1];
                }
                else if(j==0 && i>0){
                     grid[i][j] = grid[i][j] + grid[i-1][j];
                }
                else if(i!=0 && j!=0){
                     grid[i][j] = grid[i][j] + Math.min(grid[i][j-1], grid[i-1][j]);
                }
            }
        }
        return grid[grid.length-1][grid[0].length-1];
    }
}

Try this problem on Leetcode

Here, at any point we have to traverse either to the right or to the bottom, until we reach bottom right corner. But for easy solving we are going by assuming opposite of the condition by taking left or above of the current element.

1) If it is at first row and j > 0, then we are going to add current element with the left of element.
2) If it is at first column and i > 0, then we are going to add current element with the above of element.
3) If both are not equal to zero, then add current element with the minimum of left element or above element from current position.

Comments

Popular posts from this blog

Balanced Binary Tree

First Unique Character in a String

Majority Element

Smallest Range II