Monday, May 12, 2014

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


We can still use the same DP formula for Unique Paths, instead we store grid_dp[i][j] as the minimum sum to the current spot.

C++ Code:

/*
 * func: minimum_path_sum
 * goal: find the minimum path sum from top left to bottom right
 * @param grid: the grid of numbers
 * return: the minimum sum
 */
/*
 * Still the same idea as Unique Paths, but at this time we only store the
 * minimum sum instead of total paths
 * complexity: time O(m*n), space O(m*n)
 */
int minimum_path_sum(const vector<vector<int> > &grid){
    if(grid.size() == 0){
        return 0;
    }
    int m = grid.size();
    int n = grid[0].size();
    int **grid_dp =  new int* [m];
    for(int i=0; i<m; i++){
        grid_dp[i] = new int[n];
    }
    grid_dp[0][0]=grid[0][0];
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
            if(i == 0 && j > 0){
                grid_dp[i][j] = grid_dp[i][j-1] + grid[i][j];
            }else if(i > 0 && j == 0){
                grid_dp[i][j] = grid_dp[i-1][j] + grid[i][j];
            }else if(i > 0 && j > 0){
                grid_dp[i][j] = std::min(grid_dp[i-1][j],grid_dp[i][j-1]) + grid[i][j];
            }
        }
    }
    int result = grid_dp[m-1][n-1];
    for(int i=0; i<m; i++){
        delete[] grid_dp[i];
    }
    delete [] grid_dp;
    return result;
}

Python Code:

# func: find the minimum sum from the top left to bottom right
# @param grid: the grid of numbers
# @return: minimum sum
# complexity: time O(m*n), space O(m*n)
def minimum_path_sum(grid):
    if not grid:
        return 0

    m = len(grid)
    n = len(grid[0])
    grid_dp = [[1] * n for _ in xrange(m)]
    grid_dp[0][0] = grid[0][0]
    for i in xrange(m):
        for j in xrange(n):
            if i > 0 and j == 0:
                grid_dp[i][j] = grid_dp[i-1][j] + grid[i][j]
            elif i == 0 and j > 0:
                grid_dp[i][j] = grid_dp[i][j-1] + grid[i][j]
            elif i > 0 and j > 0:
                grid_dp[i][j] = min(grid_dp[i-1][j], grid_dp[i][j-1]) + grid[i][j]

    return grid_dp[m-1][n-1]

No comments:

Post a Comment