Monday, 20 November 2017

Union Find

using System;

public class UnionFindNode {
    private UnionFindNode _parent;
    private uint _rank;

    public UnionFindNode() {
        _parent = this;
    }

    public UnionFindNode Find() {
        if (!ReferenceEquals(_parent, this)) _parent = _parent.Find();
        return _parent;
    }

    public bool IsUnionedWith(UnionFindNode other) {
        if (other == null) throw new ArgumentNullException("other");
        return ReferenceEquals(Find(), other.Find());
    }

    public bool Union(UnionFindNode other) {
        if (other == null) throw new ArgumentNullException("other");
        var root1 = this.Find();
        var root2 = other.Find();
        if (ReferenceEquals(root1, root2)) return false;

        if (root1._rank < root2._rank) {
            root1._parent = root2;
        } else if (root1._rank > root2._rank) {
            root2._parent = root1;
        } else {
            root2._parent = root1;
            root1._rank++;
        }
        return true;
    }
}

No comments:

Post a Comment