有人可以向我解释这个循环中当前发生了什么吗? 这是我对 Prim 算法的作业代码的一部分。
我得到:而计数被排除不是顶点长度,部分。 我需要了解下面发生了什么。 值得一提的是,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++;
}
所以基本上这个算法所做的是遍历一个顶点列表,并根据从一个顶点到另一个顶点的成本创建一条路径。成本只是一个术语,用于解释从一个顶点到另一个顶点的困难,通常只是距离。让我们进入代码。
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
递增以跟踪当前添加的顶点数。
我希望这有帮助!不要犹豫,要求我澄清任何事情!
查看注释是否使其清除:
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++;
}