Skip to content

Instantly share code, notes, and snippets.

@jimmyahacker
Last active March 4, 2018 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmyahacker/ab824cc9d727cfd7513a5fc1e83993d3 to your computer and use it in GitHub Desktop.
Save jimmyahacker/ab824cc9d727cfd7513a5fc1e83993d3 to your computer and use it in GitHub Desktop.
Disjoint Set(Union Set)
import java.util.*;
// a DisjointSet instance stands for a disjoint set that knows all its nodes
public class DisjointSet<T> {
// the nodes in each DisjointSet instance
public static class Node<T> {
// the value of each node
public final T val;
// the parent of each node, defaut itself
private Node<T> pa = this;
public Node(T val) {
this.val = val;
}
public Node<T> getParent() {
return pa;
}
private void setParent(Node<T> pa) {
this.pa = pa;
}
}
// record all the nodes in this disjoint set
private final Set<Node<T>> setRecord;
public DisjointSet() {
this.setRecord = new HashSet<>();
}
// make a set using value
public Node<T> makeSet(T u) {
Node<T> newNode = new Node<>(u);
setRecord.add(newNode);
return newNode;
}
private Node<T> findHelper(Node<T> u) {
if (u.getParent() != u) {
u.setParent(findHelper(u.getParent()));
}
return u.getParent();
}
// finding helper
public Node<T> find(Node<T> u) {
if (setRecord.contains(u)) {
return findHelper(u);
} else {
return null;
}
}
// merge u to v
public void union(Node<T> u, Node<T> v) {
Node<T> uPa = find(u);
Node<T> vPa = find(v);
if (uPa != vPa) {
uPa.setParent(vPa);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment