简体   繁体   中英

Quick Union Algorithm in Java

This is a code in the course Algorithms by Stanford that uses Quick Union to solve dynamic connectivity.

public class QuickUnionUF {
    private int[] id;

    // Set id of each object to itself
    public QuickUnionUF(int N) {
        id = new int[N];
        for(int i = 0; i < N; i++) id[i]  i;
    }

    private int root(int i) {
        while(i != id[i]) i = id[i];
        return i;
    }

    public boolean connected(int p, int q) {
        return root(p) == root(q);
    }

    public void union(int p, int q) {
        int i = root(p);
        int j = root(q);
        id[i] = j;
    }
}

I couldn't comprehend how the root method works . Can someone please explain it to me in a step-by-step manner?

The id field is a mapping: It maps any element to the element that is closer to the root than it. So, if '8' was unioned to '6', and '6' is unioned to '4', and 4 is the root, than id[8] will be either 6 or 4.

The union(p, q) method will first find the root of elem p, then the root of elem q (how? Let's just go with the flow and say that it does, let's worry about how the root(p) function works later).

It will then update the id table: the 'pointing at the road to the root' value for the root of elem p is set to the root of elem q. In other words, what used to be p's root is now no longer a root.

That's all there is to it, now it is easy to understand how that root(p) function works: It follows the id table and continues to do so, until it finds a node whose signpost that points at the road to the root, is pointing at itself: That is a property that roots have, so that value is returned.

Note that initialize, all elements start out as their own root (the id table is initialized so that eg id[8] = 8 , id[2] = 2 , etcetera. Calls to the union method will change the id table. union(8, 2) would then have id[2] = 2 (q's root is unchanged, and initially, all elements are their own root, so root-of-2 is still just 2), but id[8] = 2 now. If you then change 2's root, say, union(2,1) , then id[8] = 2 remains unchanged, but id[2] = 1 . 8 goes to 2, but you just said to the system that the road from 2 to the root is towards 1. So, the root of 8, is now 1. The root method will tell you this, but takes 2 steps: First it 'walks' to 2, then it 'walks' to 1, then it notices the next road to take leads to itself, so it returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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