|
| 1 | +package unionfind; |
| 2 | + |
| 3 | +/** |
| 4 | + * Implements the union-find data structure (also known as disjoint-set). |
| 5 | + * This implementation uses path compression in the find operation. |
| 6 | + */ |
| 7 | +public class UnionFind { |
| 8 | + |
| 9 | + private static class Set { |
| 10 | + // the parent index of the element |
| 11 | + int parent; |
| 12 | + int rank; |
| 13 | + |
| 14 | + Set(int parent, int rank) { |
| 15 | + this.parent = parent; |
| 16 | + this.rank = rank; |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + private final Set[] sets; |
| 21 | + |
| 22 | + /** |
| 23 | + * Initializes the UnionFind structure with a specified number of elements. |
| 24 | + * Each element is initially in its own set. |
| 25 | + */ |
| 26 | + public UnionFind(int count) { |
| 27 | + sets = new Set[count]; |
| 28 | + for (int i = 0; i < count; i++) { |
| 29 | + sets[i] = new Set(i, 0); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Finds the representative (root) of the set containing 'element' |
| 35 | + * and applies path compression. |
| 36 | + * |
| 37 | + * @return the representative of the set containing 'element' |
| 38 | + */ |
| 39 | + public int find(int element) { |
| 40 | + if (element < 0 || element >= sets.length) { |
| 41 | + throw new IllegalArgumentException("Element out of bounds"); |
| 42 | + } |
| 43 | + if (sets[element].parent != element) |
| 44 | + sets[element].parent = find(sets[element].parent); |
| 45 | + return sets[element].parent; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Merges the sets containing elements 'x' and 'y'. |
| 50 | + * |
| 51 | + * @param x an element of the first set |
| 52 | + * @param y an element of the second set |
| 53 | + */ |
| 54 | + public void union(int x, int y) { |
| 55 | + if (x < 0 || x >= sets.length || y < 0 || y >= sets.length) { |
| 56 | + throw new IllegalArgumentException("Element out of bounds"); |
| 57 | + } |
| 58 | + |
| 59 | + int xRoot = find(x); |
| 60 | + int yRoot = find(y); |
| 61 | + |
| 62 | + if (xRoot != yRoot) { |
| 63 | + if (sets[xRoot].rank < sets[yRoot].rank) { |
| 64 | + sets[xRoot].parent = yRoot; |
| 65 | + } else if (sets[xRoot].rank > sets[yRoot].rank) { |
| 66 | + sets[yRoot].parent = xRoot; |
| 67 | + } else { |
| 68 | + sets[yRoot].parent = xRoot; |
| 69 | + sets[xRoot].rank++; |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments