Sunday, February 9, 2014

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.

Solution:
Basic 2-d dynamic programming.

Note: You can only move either down or right at any point in time.
public class Solution {
    public int minPathSum(int[][] grid) {
        int[][] path = new int[grid.length][grid[0].length];
        
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(i == 0 && j == 0) path[i][j] = grid[i][j];
                else if(i == 0) path[i][j] = grid[i][j] + path[i][j-1];
                else if(j == 0) path[i][j] = grid[i][j] + path[i-1][j];
                else path[i][j] = Math.min(path[i-1][j],path[i][j-1])+grid[i][j];
            }
        }
        return path[grid.length-1][grid[0].length-1];
    }
}

No comments:

Post a Comment