|
| 1 | +Problem Description |
| 2 | + |
| 3 | +/* |
| 4 | +Given a 2D integer array A of size M x N, you need to find a path from top left to bottom right which minimizes the sum of all numbers along its path. |
| 5 | + |
| 6 | +NOTE: You can only move either down or right at any point in time. |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +Input Format |
| 11 | +First and only argument is an 2D integer array A of size M x N. |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | +Output Format |
| 16 | +Return a single integer denoting the minimum sum of a path from cell (1, 1) to cell (M, N). |
| 17 | + |
| 18 | + |
| 19 | + |
| 20 | +Example Input |
| 21 | +Input 1: |
| 22 | + |
| 23 | + A = [ [1, 3, 2] |
| 24 | + [4, 3, 1] |
| 25 | + [5, 6, 1] |
| 26 | + ] |
| 27 | + |
| 28 | + |
| 29 | +Example Output |
| 30 | +Output 1: |
| 31 | + |
| 32 | + 9 |
| 33 | + |
| 34 | + |
| 35 | +Example Explanation |
| 36 | +Explanation 1: |
| 37 | + |
| 38 | + The path is 1 -> 3 -> 2 -> 1 -> 1 |
| 39 | + So ( 1 + 3 + 2 + 1 + 1) = 8 |
| 40 | + */ |
| 41 | + |
| 42 | + public class Solution { |
| 43 | + public int minPathSum(ArrayList<ArrayList<Integer>> A) { |
| 44 | + int m = A.size(); |
| 45 | + int n = A.get(0).size(); |
| 46 | + int[][] path = new int[m][n]; |
| 47 | + path[0][0] = A.get(0).get(0); |
| 48 | + for(int i = 0; i<m; i++) |
| 49 | + { |
| 50 | + for(int j = 0; j<n; j++) |
| 51 | + { |
| 52 | + if(i == 0 && j == 0) |
| 53 | + continue; |
| 54 | + if(i== 0 ) |
| 55 | + path[i][j] = A.get(i).get(j) + path[i][j-1]; |
| 56 | + else if(j == 0) |
| 57 | + path[i][j] = A.get(i).get(j) + path[i-1][j]; |
| 58 | + else |
| 59 | + path[i][j] = Math.min(path[i-1][j], path[i][j-1]) + A.get(i).get(j); |
| 60 | + } |
| 61 | + } |
| 62 | + return path[m-1][n-1]; |
| 63 | + } |
| 64 | +} |
0 commit comments