Minimum Path Sum DP Java Solution


  • 0
    V

    public class Solution {

    public int minPathSum(int[][] grid) {
    
        if(grid == null || grid.length == 0 || grid[0].length == 0){
            return 0;
        }
        
        int row = grid.length;
        int column = grid[0].length;
        
        
        int[][] sum = new int[row][column];
        sum[0][0] = grid[0][0];
        
        for(int i = 0; i < row; i++){
            for(int j = 0; j < column; j++){
                if(i == 0 && j != 0){
                    sum[i][j] = sum[i][j-1] + grid[i][j];
                }else if(i != 0 && j == 0){
                    sum[i][j] = sum[i-1][j] + grid[i][j];
                }else if(i != 0 && j != 0){
                    sum[i][j] = Math.min(sum[i-1][j]+grid[i][j], sum[i][j-1]+grid[i][j]);
                }
                
            }
        }
        return sum[row-1][column-1];
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.