Thursday, January 8, 2015

LeetCode 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.
public class Solution {
    public int minPathSum(int[][] grid) {
        // DP problem
        // S[m-1][n-1] = grid[m-1][n-1] + Math.min(S[m-1][n-2], S[m-2][n-1])
        int m = grid.length;
        
        if (m == 0)
            return 0;
        
        int n = grid[0].length;
        
        int[][] S = new int[m][n];
        
        S[0][0] = grid[0][0];
        
        if (m==1 && n==1)
            return S[0][0];
        
        // Separately consider the first row
        for (int i = 1; i < n; i++)
            S[0][i] = S[0][i-1] + grid[0][i];
        
        // Separately consider the first column    
        for (int i = 1; i < m; i++)
            S[i][0] = S[i-1][0] + grid[i][0];            
        
        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                S[i][j] = grid[i][j] + Math.min(S[i][j-1], S[i-1][j]);
                
        return S[m-1][n-1];
    }
}

No comments:

Post a Comment