|
| 1 | +package medium; |
| 2 | + |
| 3 | +import utils.CommonUtils; |
| 4 | + |
| 5 | +/**64. Minimum Path Sum |
| 6 | +
|
| 7 | + Total Accepted: 78724 |
| 8 | + Total Submissions: 219899 |
| 9 | + Difficulty: Medium |
| 10 | +
|
| 11 | +Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. |
| 12 | +
|
| 13 | +Note: You can only move either down or right at any point in time.*/ |
| 14 | +public class MinimumPathSum { |
| 15 | + /**Same idea as ClimbingStairs, also typical trick: |
| 16 | + * have to initialize the first row and the first column and start the for loop from i==1 and j==1 for the rest |
| 17 | + * of the matrix.*/ |
| 18 | + public int minPathSum(int[][] grid) { |
| 19 | + if(grid == null || grid.length == 0) return 0; |
| 20 | + |
| 21 | + int height = grid.length, width = grid[0].length; |
| 22 | + int[][] dp = new int[height][width]; |
| 23 | + dp[0][0] = grid[0][0]; |
| 24 | + for(int i = 1; i < height; i++){ |
| 25 | + dp[i][0] = dp[i-1][0] + grid[i][0]; |
| 26 | + } |
| 27 | + for(int j = 1; j < width; j++){ |
| 28 | + dp[0][j] = dp[0][j-1] + grid[0][j]; |
| 29 | + } |
| 30 | + for(int i = 1; i < height; i++){ |
| 31 | + for(int j = 1; j < width; j++){ |
| 32 | + dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j]; |
| 33 | + } |
| 34 | + } |
| 35 | + CommonUtils.printMatrix(dp); |
| 36 | + return dp[height-1][width-1]; |
| 37 | + } |
| 38 | + |
| 39 | + public static void main(String...strings){ |
| 40 | + MinimumPathSum test = new MinimumPathSum(); |
| 41 | +// int[][] grid = new int[2][2]; |
| 42 | +// grid[0][0] = 1; |
| 43 | +// grid[0][1] = 2; |
| 44 | +// grid[1][0] = 1; |
| 45 | +// grid[1][1] = 1; |
| 46 | + |
| 47 | +// int[][] grid = new int[1][1]; |
| 48 | +// grid[0][0] = 1; |
| 49 | + |
| 50 | + int[][] grid = new int[3][3]; |
| 51 | + grid[0][0] = 1; |
| 52 | + grid[0][1] = 3; |
| 53 | + grid[0][2] = 1; |
| 54 | + grid[1][0] = 1; |
| 55 | + grid[1][1] = 5; |
| 56 | + grid[1][2] = 1; |
| 57 | + grid[2][0] = 4; |
| 58 | + grid[2][1] = 2; |
| 59 | + grid[2][2] = 1; |
| 60 | + |
| 61 | + |
| 62 | + CommonUtils.printMatrix(grid); |
| 63 | + System.out.println(test.minPathSum(grid)); |
| 64 | + } |
| 65 | +} |
0 commit comments