|
| 1 | +/* |
| 2 | +https://www.techiedelight.com/find-minimum-cost-reach-last-cell-matrix-first-cell/ |
| 3 | +
|
| 4 | +From the first cell reach the last cell. Each cell has a cost. Minimize total cost. |
| 5 | +Allowed moves - right and bottom --> from (i,j) valid moves are --> (i+1,j) and (i,j+1) |
| 6 | +
|
| 7 | +Optimal substructure - |
| 8 | +cost to reach(i,j) = cost[i][j] + min( cost to reach(i-1,j), cost to reach(i,j-1) ) |
| 9 | +
|
| 10 | +Overlapping subproblems |
| 11 | +
|
| 12 | +Recursive Solution |
| 13 | +*/ |
| 14 | + |
| 15 | +public int minCost(int cost[][], int row, int col){ |
| 16 | + //row or col has reached an invalid value |
| 17 | + if(row==0 || col==0) return Integer.MAX_VALUE; |
| 18 | + |
| 19 | + //we are at the first cell --> return its value |
| 20 | + else if(row==1 && col==1) return cost[row-1][col-1]; |
| 21 | + |
| 22 | + else return cost[row-1][col-1] + Math.min(minCost(cost, row-1, col), minCost(cost, row, col-1)); |
| 23 | +} |
| 24 | + |
| 25 | +//DP Bottom up approach |
| 26 | + |
| 27 | +public int minCost(int cost[][]){ |
| 28 | + int n = cost.length; |
| 29 | + int m = cost[0].length; |
| 30 | + |
| 31 | + //pathCost[i][j] denotes the minimum cost to reach the cell(i,j) form the first cell(0,0) |
| 32 | + int pathCost[][] = new int[n][m]; |
| 33 | + |
| 34 | + for(int i=0 ; i < n ; i++){ |
| 35 | + for(int j=0 ; j < m ; j++){ |
| 36 | + pathCost[i][j] = cost[i][j]; |
| 37 | + |
| 38 | + //to reach any cell in the first row the only possible way is from left |
| 39 | + if(i==0 && j>0){ |
| 40 | + pathCost[i][j]+=pathCost[i][j-1]; |
| 41 | + } |
| 42 | + |
| 43 | + //to reach any cell in the first column the only possible way is from top |
| 44 | + else if(j==0 && i>0){ |
| 45 | + pathCost[i][j]+=pathCost[i-1][j]; |
| 46 | + } |
| 47 | + |
| 48 | + //consider the path cost from the top and left --> choose minimum |
| 49 | + else{ |
| 50 | + pathCost[i][j]+=Math.min(pathCost[i-1][j],pathCost[i][j-1]); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + //stores the minimum path cost |
| 56 | + return pathCost[n][m]; |
| 57 | +} |
| 58 | + |
| 59 | +/* |
| 60 | +Time and Space Complexity - O(n*m) |
| 61 | +
|
| 62 | +*/ |
0 commit comments