public static int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] pathsum = new int[m][n];
    	for (int i = m - 1; i >= 0; i--) {
        	for (int j = n - 1; j >= 0; j--) {
        		if (i == m - 1 && j == n - 1) pathsum[i][j] = grid[i][j];
        		else if (i == m - 1) pathsum[i][j] = pathsum[i][j + 1] + grid[i][j];
        		else if (j == n - 1) pathsum[i][j] = pathsum[i + 1][j] + grid[i][j];
        		else {
        			int right = pathsum[i][j + 1];
        			int down = pathsum[i + 1][j];
        			pathsum[i][j] = right > down ? down + grid[i][j] : right + grid[i][j];
        		}
        	}
        }
    	return pathsum[0][0];
    }