Union-Find
https://algs4.cs.princeton.edu/15uf/
Dynamic Connectivity Problem
a dynamic connectivity structure is a data structure that dynamically maintains information about the connected components of a graph.
Union-Find API
Implementations
Quick-Find (eager approach)
Data Structure:
- Integer array id[ ] of size N
- Interpretation: p and q are connected iff they have the same id
- default config: each id equals to its index
Find: check if p and q have the same id
Union: To merge components contatining p and q, change all entires whose id equals id[p] to id[q]
Implementation
public class QuickFindUF {
private int[] id; // id[i] = component identifier of i
private int count; // number of components
/**
constructor
*/
public QuickFindUF(int n) {
count = n;
id = new int[n];
for (int i = 0; i < n; i++)
id[i] = i;
}
/**
* Returns the number of sets.
*/
public int count() {
return count;
}
/**
* Returns the canonical element of the set containing element p.
*/
public int find(int p) {
validate(p);
return id[p];
}
// validate that p is a valid index
private void validate(int p) {
int n = id.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));
}
}
/**
* Returns true if the two elements are in the same set.
*/
@Deprecated
public boolean connected(int p, int q) {
validate(p);
validate(q);
return id[p] == id[q