Matrix:
6 9 3
4 8 2
3 5 10
You can start at any integer in the first row, you can only go down the matrix and add the left,right or directly below the previous number. For example, you start at 9 you can either go to 4,8, or 2. I figured out how to get the result matrix which is
Matrix:
6 9 3
10 11 5
13 10 15
The shortest path is clearly 3>2>5 which corresponds to the 3>5>10 on the result matrix. I want to store the coordinates of the cheapest path in an ArrayList.In this case it would be [0,2,1,2,2,1]. This is what I have so far.My question is where do you add the values into the ArrayList?
private static ArrayList<Integer> minCost(int cost[][])
{
ArrayList<Integer> minValues = new ArrayList<>();
int n = cost.length;
int m = cost[0].length;
int i, j;
int tc[][] = new int[m][n];
for (i = 0; i <= n - 1; i++) {
tc[0][i] = cost[0][i];
}
for (i = 1;i <= n - 1; i++) {
for (j = 0; j <= m - 1; j++) {
if(j ==0){
tc[i][j] = Math.min(tc[i - 1][j],
tc[i-1][j + 1])
+ cost[i][j];
}
else if(j == m-1){
tc[i][j] = Math.min(tc[i - 1][j - 1],
tc[i - 1][j])
+ cost[i][j];
}
else{
tc[i][j] = min(tc[i - 1][j - 1],
tc[i - 1][j],
tc[i-1][j + 1])
+ cost[i][j];
}
}
}
return minValues;
}