Created
January 13, 2023 22:10
-
-
Save rubenhak/fb328aa55397a4795da29b714d2d0b36 to your computer and use it in GitHub Desktop.
JavaScript Disjoint Set Union
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 DisjointSetUnion | |
{ | |
constructor() | |
{ | |
this.map = new Map(); | |
} | |
find(x) | |
{ | |
let other = this.map.has(x) ? this.map.get(x) : x; | |
if (other != x) | |
{ | |
other = this.find(other); | |
this.map.set(x, other); | |
} | |
return other; | |
} | |
union(x, y) | |
{ | |
this.map.set(this.find(x), this.find(y)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment