From b76b5c35483a2261efb2741ee75f24a179fa7db7 Mon Sep 17 00:00:00 2001 From: bringani Date: Thu, 21 Oct 2021 12:22:01 -0300 Subject: [PATCH] feat: add Disjoint Set Data Structure using Java --- Data Structures/DisjointSet/DisjointSet.java | 42 ++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Data Structures/DisjointSet/DisjointSet.java diff --git a/Data Structures/DisjointSet/DisjointSet.java b/Data Structures/DisjointSet/DisjointSet.java new file mode 100644 index 0000000..9e86044 --- /dev/null +++ b/Data Structures/DisjointSet/DisjointSet.java @@ -0,0 +1,42 @@ +public class DisjointSet { + private int[] parent; + + public DisjointSet(int n) { + parent = new int[n]; + for (var i = 0; i < n; i++) { + parent[i] = i; + } + } + + public int find(int x) { + if (x == parent[x]) { + return x; + } + // compress the paths + return parent[x] = find(parent[x]); + } + + public void union(int x, int y) { + var px = find(x); + var py = find(y); + if (px != py) { + parent[px] = py; + } + } + // number of groups + public int size() { + int ans = 0; + for (int i = 0; i < parent.length; ++ i) { + if (i == parent[i]) ans ++; + } + return ans; + } + + public static void main(String[] args) { + var ds = new DisjointSet(5); + System.out.println(ds.find(3)); + + ds.union(3, 4); + System.out.println(ds.find(3)); // after join, 3's parent is 4. + } + } \ No newline at end of file