简体   繁体   English

Java while循环神秘迭代

[英]Java while loop mysterious iteration

Can somebody teach me how the while loop in find method is working?有人可以教我 find 方法中的 while 循环是如何工作的吗? Does that somehow iterates the parent array from 0 to the endpoint automatically?这是否会以某种方式自动将父数组从 0 迭代到端点? until paren[i]?= i?直到 paren[i]?= i?

static int find(int i) 
{ 
    while (parent[i] != i) 
        i = parent[i]; 
    return i; 
} 
  
// Finds MST using Kruskal's algorithm 
static void kruskalMST(int cost[][]) 
{ 
    int mincost = 0; // Cost of min MST. 
  
    // Initialize sets of disjoint sets. 
    for (int i = 0; i < V; i++) 
        parent[i] = i; 
  
    // Include minimum weight edges one by one 
    int edge_count = 0; 
    while (edge_count < V - 1) 
    { 
        int min = INF, a = -1, b = -1; 
        for (int i = 0; i < V; i++) 
        { 
            for (int j = 0; j < V; j++)  
            { 
                if (find(i) != find(j) && cost[i][j] != 0 && cost[i][j] < min)  
                { 
                    min = cost[i][j]; 
                    a = i; 
                    b = j; 
                } 
            } 
        } 

It's difficult to see what you're not grasping - it executes as written.很难看出你没有掌握什么——它按照书面规定执行。

find is called with some value of i findi的某个值调用

Does the i'th entry in the parent array contain the value i ? parent数组中的第 i 个条目是否包含值i Yes, then control proceeds to the return statement and we're done.是的,然后控制继续执行 return 语句,我们就完成了。

Otherwise, set the value in i to the value from the i'th entry of the 'parent' array.否则,将i中的值设置为“父”数组的第 i 个条目中的值。

Does the i'th entry in the parent array contain the value i ? parent数组中的第 i 个条目是否包含值i
Yes, then control proceeds to the return statement and we're done.是的,然后控制继续执行 return 语句,我们就完成了。

Otherwise, set the value in i to the value from the i'th entry of the 'parent' array.否则,将i中的值设置为“父”数组的第 i 个条目中的值。

… and keep doing this... ......并继续这样做......

The overall logic seems to be that each entry in the parent array is supposed to identify its parent entry, except that the topmost entry has itself for its parent.总体逻辑似乎是parent数组中的每个条目都应该标识其父条目,除了最上面的条目具有自己的父条目。

However, since all entries in parent are initialized such that the i'th entry contains i , and nothing changes that, it seems the code shown is incomplete.但是,由于parent中的所有条目都已初始化,因此第 i 个条目包含i ,并且没有任何更改,因此显示的代码似乎不完整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM