我在使用Java遍历加权邻接矩阵时遇到了问题。我想做的是使用Prim算法从矩阵中获取最小生成树的权重。
目前我的代码如下:
public int findPrim(int[][] matrix) {
ArrayList < Integer > checkThese = new ArrayList < > ();
checkThese.add(0); //Starting vertex.
boolean[] checked = new boolean[graph.vertexCount()];
int w = 0;
int column = 0;
int row = 0;
int smallest = 0;
for (Iterator < Integer > it = checkThese.Iterator(); it.hasNext();) {
smallest = Integer.MAX_VALUE;
for (int k = 0; k < graph.vertexCount(); k++) {
if ((matrix[r][k] < smallest) && matrix[r][k] != 0 && !checked[k - 1]) {
smallest = matrix[r][k];
column = k;
}
}
if (smallest != Integer.MAX_VALUE) {
w += smallest;
checkThese.add(column);
checked[column] = true;
}
}
return w;
}
我知道如何在理论上遍历矩阵,但我在实现中遇到了问题。具体来说,由于我需要在迭代列表时更新
checkThese
,所以我需要使用一个迭代器,就像我尝试做的那样。然而,现在的问题是我无法想出一种方法来获取矩阵的r
坐标,这是我后来需要的。该方法还缺少其他一些东西,但我的主要问题是如何在更新正在检查的矩阵行列表时遍历矩阵。我的邻接矩阵形式为:
A B C D E
A 0 4 2 8 0
B 0 0 5 6 7
C 0 0 0 9 3
D 0 0 0 0 1
E 0 0 0 0 0
计划从行
A
开始,选择最小的边(2)。然后我会排除列C
,接下来检查行A
和C
等,直到排除所有列,因此检查所有边缘。
let cost = matrix[min(v, w)][max(v, w)]
这一行的含义呢?我不确定我是否正确理解了语法。 - user1290164v
和w
中的最小值,对于列选择最大值,那么我认为我会遇到同样的问题,即如何获取v
属性的值,如果我正在使用迭代器实现for v in checkThese
。 - user1290164