Template for Disjoint set - Union Find - Java

Mani
Mani
Educating everyone with the beauty of programming!!

Template for Disjoint set - Union Find - Java

Disjoint Sets with Arrays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class DSU {
    int[] parent;
    public DSU() {
        parent = new int[10001];
        for (int i = 0; i <= 10000; ++i)
            parent[i] = i;
    }
    public int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
    public void union(int x, int y) {
        parent[find(x)] = find(y);
    }
}

Reference:

https://leetcode.com/problems/accounts-merge/solution/ https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/solution/