首页 > 代码库 > Minimum Path Sum

Minimum Path Sum

public class Solution {
    /**
     * @param grid: a list of lists of integers.
     * @return: An integer, minimizes the sum of all numbers along its path
     */
    public int minPathSum(int[][] grid) {
        // write your code here
        if (grid == null || grid.length == 0) {
            return 0;
        }
        
        if (grid[0] == null || grid[0].length == 0) {
            return 0;
        }
        
        int nRow = grid.length;
        int nCol = grid[0].length;
        
        int[][] f = new int[nRow][nCol]; //f[x][y]: minimum path sum from (0, 0) to (x, y)
        f[0][0] = grid[0][0];
        for (int i = 1; i < nCol; i++) {
            f[0][i] = f[0][i - 1] + grid[0][i];
        }
        for (int i = 1; i < nRow; i++) {
            f[i][0] = f[i - 1][0] + grid[i][0];
        }
        
        for (int i = 1; i < nRow; i++) {
            for (int j = 1; j < nCol; j++) {
                f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + grid[i][j];
            }
        }
        
        return f[nRow - 1][nCol - 1];
    }
}

 

Minimum Path Sum