并查集Union Find

对于并查集的理解?

a.并查集用于处理连接问题,可以非常快地判断出网络中节点的连接状态.能够快速实现数学中的集合类的并操作.
b.并查集其实也是一种树的数据结构,不过其与常规的BST不同,并查集的树结构是从子节点到父节点的一个访问顺序.

并查集的设计思路

并查集涉及到的核心方法是连接判断和并集运算.

并查集的实现:

1.直接基于数组实现. 实现Quick Find


数组实现原理图

实现代码:

/**
 * class Union Find based on array
 * @author Administrator
 *
 */
public class UnionFindEditon_QuickFind implements UnionFind{
    private int[] id;
    
    public UnionFindEditon_QuickFind(int size) {
        id = new int[size];     
        for (int i = 0; i < size; i++) {
            id[i] = i;
        }
    }
    
    @Override
    public int getSize() {
        return id.length;
    }
    
    @Override
    public void unionElements(int p, int q) {
        if (find(p) == find(q)) {
            return;
        }
        /**
         * assign the type of q to p
         */
        int pID = id[p];
        id[p] = id[q];
        /**
         * the step make the Degree-complex of the operation rise to O(n)
         */
        for (int i = 0; i < id.length; i++) {
            if (id[i] == pID) {
                id[i] = id[q];
            }
        }
    }
    
    @Override
    public boolean isConnected(int p, int q) {
        return find(p)==find(q);
    }
    
    
    public int find(int index) {
        if (index < 0 || index >= id.length ) {
            throw new IllegalArgumentException("index is out of boundary");
        }
        return id[index];
    }
}

2.基于数组实现,但数组元素之间存在对应关系.实现Quick Union


节点之间的关系
在数组中子父节点用parent[index]表达

代码实现:

/**
 * class UnionFind based on tree module
 * @author Administrator
 *
 */
public class UnionFindEditon_QuickUnion implements UnionFind {
    private int[] parent;
    
    public UnionFindEditon_QuickUnion(int size) {
        parent = new int[size];
        for (int i = 0; i < size; i++) {
            parent[i] = i;
        }
    }
    
    @Override
    public int getSize() {
        return parent.length;
    }
    
    
    /**
     * determines whether two elements are connected
     */
    @Override
    public boolean isConnected(int p, int q) {
        if (find(p) == find(q)) {
            return true;
        }
        return false;
    }
    
    /**
     * method --> union the two elements
     */
    @Override
    public void unionElements(int p, int q) {
        if (find(p) == find(q)) {
            return;
        }
        else {
            parent[find(p)] = find(q);
        }
    }
    
    /**
     * get the root of the target index
     * @param index
     * @return
     */
    public int find(int index) {
          if(index < 0 || index >= parent.length)
              throw new IllegalArgumentException("p is out of bound.");
        if (parent[index] != index ) {
            index = parent[index];
        }
        return index;
    }
}

你可能感兴趣的:(并查集Union Find)