Matrix:
6 9 3
4 8 2
3 5 10
你可以从第一行的任意整数开始,只能向下移动到左、右或直接下方的前一个数字,并将它们相加。例如,你从9开始,可以选择移动到4、8或2。
我已经想出如何得到结果矩阵,即:
Matrix:
6 9 3
10 11 5
13 10 15
最短路径显然是3>2>5,对应于结果矩阵上的3>5>10。我想把最便宜的路径坐标存储在ArrayList中。在这种情况下,它将是[0,2,1,2,2,1]。目前为止,我的问题是在什么地方将值添加到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;
}