Last active
January 25, 2023 00:40
-
-
Save ddoronin/3fa7544e23b9a50d52556eae671b6bd9 to your computer and use it in GitHub Desktop.
Union Find
This file contains hidden or 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
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