Simple Java Solution


  • 0
    Z
    public class Solution {
        public int minPathSum(int[][] grid) {
            if (grid == null || grid.length == 0) {
                return -1;
            }
    
            int m = grid.length;
            int n = grid[0].length;
            int[][] path = new int[m][n];
            path[0][0] = grid[0][0];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (i == 0 && j > 0) {
                        path[i][j] = grid[i][j] + path[i][j - 1];
                    } else if (j == 0 && i > 0) {
                        path[i][j] = grid[i][j] + path[i - 1][j];
                    } else if (i > 0 && j > 0) {
                        path[i][j] = grid[i][j] + Math.min(path[i - 1][j], path[i][j - 1]);
                    }
                }
            }
            return path[m - 1][n - 1];
        }
    }
    

Log in to reply
 

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