一个并查集对象
实现并查集的查找、合并、类别size
class UF{ constructor(n){ this.parent=Array(n) this.size=[] for (let i = 0; i < n; i++) { this.parent[i] = i; this.size[i] = 1; } } find(x){ const parent=this.parent; if (parent[x] != x) { parent[x] = this.find(parent[x]); } return parent[x]; } merge(x,y){ x=this.find(x) y=this.find(y) if (x == y) return; this.parent[y] = x; // 注意 别写反了 this.size[x] += this.size[y]; } } const d=new UF(4) d.merge(1,2);//1、2属于同一个集合 d.merge(3,2);//3、2属于同一个集合 //0属于集合0 console.log(d.find(0)) //1、2、3属于同一个集合3,下面都输出3 console.log(d.find(1)); console.log(d.find(2)) console.log(d.find(3))