JS刷题-并查集
并查集数据结构
class UnionFind {
constructor(n) {
this.count = n
this.parent = new Array(n).fill(0).map((_, index) => index)
}
union(p, q) {
let rootP = this.find(p)
let rootQ = this.find(q)
if (rootP == rootQ) return
this.parent[rootQ] = rootP
this.count--
}
find(x) {
if (this.parent[x] != x) {
this.parent[x] = this.find(this.parent[x])
}
return this.parent[x]
}
isConnected(p, q) {
let rootP = this.find(p)
let rootQ = this.find(q)
return rootP == rootQ
}
count() {
return this.count
}
}
const u = new UnionFind(edges.length + 1)
for (let edge of edges) {
const r1 = u.find(edge[0])
const r2 = u.find(edge[1])
if (r1 == r2) return edge
u.union(r1, r2)
}
return []