@easy-data-structure-js/union-find
Version:
A TypeScript implementation of union-find (disjoint set) data structure
2 lines (1 loc) • 604 B
JavaScript
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class e{parent;rank;count;constructor(t){this.parent=Array.from({length:t},(r,n)=>n),this.rank=new Array(t).fill(0),this.count=t}find(t){return this.parent[t]!==t&&(this.parent[t]=this.find(this.parent[t])),this.parent[t]}union(t,r){const n=this.find(t),i=this.find(r);return n===i?!1:(this.rank[n]<this.rank[i]?this.parent[n]=i:this.rank[n]>this.rank[i]?this.parent[i]=n:(this.parent[i]=n,this.rank[n]++),this.count--,!0)}connected(t,r){return this.find(t)===this.find(r)}getCount(){return this.count}}exports.UnionFind=e;