Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions MinCostPath.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* DP based solution to find minimum cost to reach last cell of a weighted cost
* matrix from its first cell
*
* @author vavasing
*/
public class MinCostPath {
public static int minCost(int[][] costMatrix, int m, int n) {
// base case, matrix size 0.
if (n == 0 || m == 0) {
return Integer.MAX_VALUE;
}

// For 1x1 matrix return weight as is.
if (m == 1 && n == 1) {
return costMatrix[0][0];
}

// Add cost of current cell to recursive solution of minimum of
// path from adjacent left cell, adjacent top cell to cirrent cell.
return Integer.min(minCost(costMatrix, m - 1, n), minCost(costMatrix, m, n - 1))
+ costMatrix[m - 1][n - 1];
}

// Tester method
public static void main(String[] args)
{
int[][] costMatrix =
{
{ 3, 6, 8, 6, 5 },
{ 6, 7, 3, 5, 2 },
{ 3, 2, 1, 2, 4 },
{ 7, 1, 7, 6, 7 },
{ 2, 9, 2, 9, 3 }
};

System.out.print("The minimum cost : " +
minCost(costMatrix, costMatrix.length, costMatrix[0].length));
}
}