Union Find---Some Thoughts

Union Find is not a phrase, it’s literally two words: Union and Find.
Union: we union all the vertices that belongs to the same connected graph in to different sets
Find: find the fixed vertices are in which sets(connected graphs)

in summay, union find maintain a bunch of connected graphs.

Now, as a high level data structure, which data structure we are gonna use to implement Union Find?
we can use array.
Now, we needs to implement two very important methods for Union Find: find() and union().

public int find(int element) { //find the graph index which current elements belongs to, but how? we need to find it's root
//how to find out some elements' root? one node's root is itself, then this node is root
    if (roots[element] == element) { //if it is root
        return element;
    }
    
    int father = element;
    while (roots[father] != father) {
        father = roots[father];
    }
    
    return father;
}
public void union(int element1, int element2) {  //union two element belongs to different graph into one
    int root1 = find(element1);
    int root2 = find(element2);
    
    if (root1 != root2) {
        roots[root1] = root2; //set root1's root as root2
    }
}

In summary, it is kind of geneius for people to think of union found, which uses an array to represent many graphs.

posted @ 2020-04-27 04:06  EvanMeetTheWorld  阅读(17)  评论(0)    收藏  举报