Skip to content

Instantly share code, notes, and snippets.

@jakubtuchol
Created November 5, 2016 21:59
Show Gist options
  • Select an option

  • Save jakubtuchol/41527a25900d358d524abdacaa846f58 to your computer and use it in GitHub Desktop.

Select an option

Save jakubtuchol/41527a25900d358d524abdacaa846f58 to your computer and use it in GitHub Desktop.
package com.jakubtuchol.algorithms.questions;
/**
* Created by jakub on 12/3/15.
*/
public class QuickUnion {
private int[] parent;
private int[] size;
private int count;
public QuickUnion(int N) {
count = N;
parent = new int[N];
size = new int[N];
for (int i = 0; i < N; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int count() {
return count;
}
public int find(int p) {
while (p != parent[p])
p = parent[parent[p]];
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
} else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
}
Contact GitHub API Training Shop Blog About
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment