Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Created December 19, 2019 02:07
Show Gist options
  • Save gkucmierz/37e7fc8a90342516c1cf61011d8f551e to your computer and use it in GitHub Desktop.
Save gkucmierz/37e7fc8a90342516c1cf61011d8f551e to your computer and use it in GitHub Desktop.
// union find
// quick-union with path compression
const unionFind = n => {
const arr = new Uint32Array(n);
for (let i = 0; i < n; ++i) {
arr[i] = i;
}
const root = p => {
while (arr[p] !== p) {
arr[p] = arr[arr[p]];
p = arr[p];
}
return p;
};
const union = (p, q) => {
arr[root(p)] = root(q);
};
const connected = (p, q) => {
return root(p) === root(q);
};
return {union, connected};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment