有人可以向我解释一下此循环中当前正在发生什么吗? 这是我分配Prim算法的代码的一部分。
我得到了:而countIcluded不是vertices.length,一部分。
我需要了解下面发生的情况。
值得一提的是included
是布尔数组。
期望我是新手,因为我是我,请解释得尽可能简单(如果可能),以便我能理解基本知识。
while (countIncluded != vertices.length) {
// find the not included vertex with minimum cost
int u = -1;
for (int i = 0; i < vertices.length; i++) {
if (!included[i]) {
if (u == -1 || C[u] > C[i])
u = i;
}
}
// include in MST
included[u] = true;
countIncluded++;
}
答案 0 :(得分:3)
因此,基本上,该算法的作用是遍历一个顶点列表,并根据从一个顶点到另一个顶点的成本创建一条路径。成本只是一个术语,用以解释从一个顶点到另一个顶点的困难,通常只是距离。让我们进入代码。
while (countIncluded != vertices.length) {
我知道您说过您了解这意味着什么,但我仍然会继续讨论。这种while循环将确保您遍历数组中的每个顶点,从而使每个顶点至少相互连接。
int u = -1;
for (int i = 0; i < vertices.length; i++) {
我将这两行结合在一起,因为第一行没有做太多事情。变量u
是有关当前顶点的索引。最初将其设置为-1,因为这不是数组中的有效位置。下一行for
循环仅循环遍历给定数组中的每个顶点。
if (!included[i]) {
if (u == -1 || C[u] > C[i])
u = i;
第一行只是检查以查看i
的当前值或当前顶点是否已包含在树中。如果是这样,我们不需要再次检查,然后继续下一个。下一行首先检查u
是否等于-1。如上所述,-1只是一个临时占位符值,此检查可确保它始终指向有效的顶点。第二项检查是检查u
的成本是否大于i
的成本。这实际上是在做算法。它基本上是在获取u
或临时顶点的成本。然后,它根据i
的成本进行检查。如果i
的成本小于u
的成本,则将u
设置为i
。这样,它将找到成本最低的顶点,因为它会记住整个过程中u
的值。
included[u] = true;
countIncluded++;
第一行将数组中u
的索引设置为true。这将确保不会在您的算法中再次对其进行检查,以防止在每次迭代中无休止地循环检查相同的顶点。之后,countIncluded
递增以跟踪当前添加的顶点数量。
我希望这会有所帮助!不要犹豫,问我要澄清什么!
答案 1 :(得分:1)
查看是否清除了注释:
while (countIncluded != vertices.length) {
//u represents a previous i value
int u = -1; //value serves as flag for "first time use"
//the purpose of this loop is to iterate over included array, which presumably
//if of the same length as vertices.
for (int i = 0; i < vertices.length; i++) {
if (!included[i]) { //execute if the value of included[i] is false
/* execute if one of these apply:
u value is -1 : meaning that it is the first time
included[i] is false (and there is not previous value to compare to).
OR C[u] > C[i] : previous vertex value > current vertex value
*/
if (u == -1 || C[u] > C[i])
u = i; //keep i value, the index of the lowest vertex
//value so far
}
}
//at the end of the for loop u is the index of the lowest C[u]
included[u] = true;
countIncluded++;
}