Created
June 27, 2018 13:04
-
-
Save dkohlsdorf/acd2d0ee0c88e8eec25c2f7357992456 to your computer and use it in GitHub Desktop.
Union Find Data Structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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