Skip to content

Instantly share code, notes, and snippets.

@dkohlsdorf
Created June 27, 2018 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkohlsdorf/acd2d0ee0c88e8eec25c2f7357992456 to your computer and use it in GitHub Desktop.
Save dkohlsdorf/acd2d0ee0c88e8eec25c2f7357992456 to your computer and use it in GitHub Desktop.
Union Find Data Structure
public class UnionFind {
private int id[];
private int count;
public UnionFind(int N) {
count = N;
id = new int[N];
for(int i = 0; i < N; i++) {
id[i] = i;
}
}
public int count() {
return count;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int find(int p) {
while(p != id[p]) p = id[p];
return p;
}
public void union(int p, int q) {
int i = find(p);
int j = find(q);
if(i != j) {
id[i] = j;
count--;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment