|
| 1 | +package DynamicProgramming; |
| 2 | + |
| 3 | +/* |
| 4 | +Given the following grid with length m and width n: |
| 5 | +\---\---\---\ (n) |
| 6 | +\ 1 \ 3 \ 1 \ |
| 7 | +\---\---\---\ |
| 8 | +\ 1 \ 5 \ 1 \ |
| 9 | +\---\---\---\ |
| 10 | +\ 4 \ 2 \ 1 \ |
| 11 | +\---\---\---\ |
| 12 | +(m) |
| 13 | +Find the path where its sum is the smallest. |
| 14 | +
|
| 15 | +All numbers given are positive. |
| 16 | +The Time Complexity of your algorithm should be smaller than or equal to O(mn). |
| 17 | +The Space Complexity of your algorithm should be smaller than or equal to O(mn). |
| 18 | +You can only move from the top left corner to the down right corner. |
| 19 | +You can only move one step down or right. |
| 20 | +
|
| 21 | +EXAMPLE: |
| 22 | +INPUT: grid = [[1,3,1],[1,5,1],[4,2,1]] |
| 23 | +OUTPUT: 7 |
| 24 | +EXPLANATIONS: 1 + 3 + 1 + 1 + 1 = 7 |
| 25 | +
|
| 26 | +For more information see https://www.geeksforgeeks.org/maximum-path-sum-matrix/ |
| 27 | +*/ |
| 28 | +public class MinimumPathSum { |
| 29 | + |
| 30 | + public void testRegular() { |
| 31 | + int[][] grid = { |
| 32 | + {1, 3, 1}, |
| 33 | + {1, 5, 1}, |
| 34 | + {4, 2, 1} |
| 35 | + }; |
| 36 | + System.out.println(minimumPathSum(grid)); |
| 37 | + } |
| 38 | + |
| 39 | + public void testLessColumns() { |
| 40 | + int[][] grid = { |
| 41 | + {1, 2}, |
| 42 | + {5, 6}, |
| 43 | + {1, 1} |
| 44 | + }; |
| 45 | + System.out.println(minimumPathSum(grid)); |
| 46 | + } |
| 47 | + |
| 48 | + public void testLessRows() { |
| 49 | + int[][] grid = { |
| 50 | + {2, 3, 3}, |
| 51 | + {7, 2, 1} |
| 52 | + }; |
| 53 | + System.out.println(minimumPathSum(grid)); |
| 54 | + } |
| 55 | + |
| 56 | + public void testOneRowOneColumn() { |
| 57 | + int[][] grid = {{2}}; |
| 58 | + System.out.println(minimumPathSum(grid)); |
| 59 | + } |
| 60 | + |
| 61 | + public static int minimumPathSum(int[][] grid) { |
| 62 | + int m = grid.length, n = grid[0].length; |
| 63 | + if (n == 0) { |
| 64 | + return 0; |
| 65 | + } |
| 66 | + int[][] dp = new int[m][n]; |
| 67 | + dp[0][0] = grid[0][0]; |
| 68 | + for (int i = 0; i < n - 1; i++) { |
| 69 | + dp[0][i + 1] = dp[0][i] + grid[0][i + 1]; |
| 70 | + } |
| 71 | + for (int i = 0; i < m - 1; i++) { |
| 72 | + dp[i + 1][0] = dp[i][0] + grid[i + 1][0]; |
| 73 | + } |
| 74 | + for (int i = 1; i < m; i++) { |
| 75 | + for (int j = 1; j < n; j++) { |
| 76 | + dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; |
| 77 | + } |
| 78 | + } |
| 79 | + return dp[m - 1][n - 1]; |
| 80 | + } |
| 81 | +} |
0 commit comments