- Any numbers not at the top row or left column of a int 2d array can be computed by taking the min of its top of left neighbour using this algorithmn from using dynamic programming: https://leetcode.com/discuss/17111/my-java-solution-using-dp-and-no-extra-space
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import java.util.*; public class HelloWorld{ public static void main(String []args){ int[][] multi = new int[][]{ { 10, 10, 10}, { 2, 2, 2}, { 2, 2, 2}, }; System.out.println(minPathSum(multi)); } public static int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // this is our starting top left corner, no need to change number in place // set it back to what it was and we will never enter here again if (i == 0 && j == 0) { grid[i][j] = grid[i][j]; } // if we are looking at the top row of numbers, compute a new number // for the current grid[0][x] by adding the left neighbour grid[0][j - 1] with current // grid[0][x] else if (i == 0 && j != 0) { grid[i][j] = grid[i][j] + grid[i][j - 1]; } // if we are looking at the left column of numbers, compute a new number // for the current grid[x][0] by adding the top neighbour grid[i - 1][0] with current // grid[x][0] else if (i != 0 && j == 0) { grid[i][j] = grid[i][j] + grid[i - 1][j]; } // Else we are looking at the numbers not at the topmost row or leftmost column. // This means these numbers can be computer by adding the current grid[i][j] with the // minimum of its top grid[i][j - 1] or left grid[i - 1][j] neighbour. else { grid[i][j] = grid[i][j] + Math.min(grid[i][j - 1], grid[i - 1][j]); } } } // finally after all the addition and modifying each number of the original grid // in place, the answer of the least sum for the path from top left corner to // bottom right corner will be at grid[m - 1][n - 1] and so return the sum as int return grid[m - 1][n - 1]; } } |