Skip to content

Instantly share code, notes, and snippets.

@ddoronin
Last active January 25, 2023 00:40
Show Gist options
  • Save ddoronin/3fa7544e23b9a50d52556eae671b6bd9 to your computer and use it in GitHub Desktop.
Save ddoronin/3fa7544e23b9a50d52556eae671b6bd9 to your computer and use it in GitHub Desktop.
Union Find
class UF {
public vertices: Array<number>;
constructor(n: number) {
this.vertices = Array.from({length: n}, (_, i) => i);
}
union(x: number, y: number){
this.vertices[this.find(x)] = this.find(y);
}
find(x: number) {
return x === this.vertices[x]? x: this.find(this.vertices[x]);
}
connected(x: number, y: number) {
return this.find(x) === this.find(y);
}
count() {
return this.vertices.filter((p, i) => p === i).length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment