UNPKG

@easy-data-structure-js/union-find

Version:

A TypeScript implementation of union-find (disjoint set) data structure

2 lines (1 loc) 808 B
(function(i,r){typeof exports=="object"&&typeof module<"u"?r(exports):typeof define=="function"&&define.amd?define(["exports"],r):(i=typeof globalThis<"u"?globalThis:i||self,r(i.UnionFind={}))})(this,(function(i){"use strict";class r{parent;rank;count;constructor(t){this.parent=Array.from({length:t},(s,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,s){const n=this.find(t),e=this.find(s);return n===e?!1:(this.rank[n]<this.rank[e]?this.parent[n]=e:this.rank[n]>this.rank[e]?this.parent[e]=n:(this.parent[e]=n,this.rank[n]++),this.count--,!0)}connected(t,s){return this.find(t)===this.find(s)}getCount(){return this.count}}i.UnionFind=r,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})}));