mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-08 18:32:56 +08:00
Add Disjoint Set (#2684)
This commit is contained in:
32
DataStructures/DisjointSets/DisjointSets.java
Normal file
32
DataStructures/DisjointSets/DisjointSets.java
Normal file
@ -0,0 +1,32 @@
|
||||
package DataStructures.DisjointSets;
|
||||
|
||||
public class DisjointSets<T> {
|
||||
public Node<T> MakeSet(T x) {
|
||||
return new Node<T>(x);
|
||||
};
|
||||
|
||||
public Node<T> FindSet(Node<T> node) {
|
||||
if (node != node.parent) {
|
||||
node.parent = FindSet(node.parent);
|
||||
}
|
||||
|
||||
return node.parent;
|
||||
}
|
||||
|
||||
public void UnionSet(Node<T> x, Node<T> y) {
|
||||
Node<T> nx = FindSet(x);
|
||||
Node<T> ny = FindSet(y);
|
||||
|
||||
if (nx == ny) {
|
||||
return;
|
||||
}
|
||||
if (nx.rank > ny.rank) {
|
||||
ny.parent = nx;
|
||||
} else if (ny.rank > nx.rank) {
|
||||
nx.parent = ny;
|
||||
} else {
|
||||
nx.parent = ny;
|
||||
ny.rank++;
|
||||
}
|
||||
}
|
||||
}
|
11
DataStructures/DisjointSets/Node.java
Normal file
11
DataStructures/DisjointSets/Node.java
Normal file
@ -0,0 +1,11 @@
|
||||
package DataStructures.DisjointSets;
|
||||
|
||||
public class Node<T> {
|
||||
public int rank;
|
||||
public Node<T> parent;
|
||||
public T data;
|
||||
public Node(T data) {
|
||||
this.data = data;
|
||||
parent = this;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user