Thursday, January 30, 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.
My Code:
 int minPathSum(vector<vector<int> > &grid) {
        if(grid.empty()) return 0;
        int width = grid[0].size();
        int height = grid.size();
        int table[height][width];
        table[0][0] = grid[0][0];
        for(int i = 0; i < height; ++i){
            for(int j = 0; j < width; ++j){
                if(i == 0 && j != 0 )
                    table[0][j] = table[0][j-1]+grid[0][j];
                else if(j == 0 && i != 0)
                    table[i][0] = table[i-1][0]+grid[i][0];
                else if(i != 0 && j != 0){
                    table[i][j] = min(table[i-1][j], table[i][j-1]) + grid[i][j];
                }
            }
        }
        return table[height-1][width-1];
    }

No comments:

Post a Comment