/*
* @Author: zhihui
* @Date: 2021-11-30 21:16:30
* @LastEditTime: 2021-11-30 09:49:11
* @LastEditors: your name
* @Description: In User Settings Edit
* @FilePath: \ECloud-H5d:\Test\网络连通数目-并查集.js
*/
var makeConnected = function(n, connections) {
if (connections.length < n - 1) {
return -1;
}
const uf = new UnionFind(n);
for (const conn of connections) {
uf.unite(conn[0], conn[1]);
}
return uf.result - 1;
};
class UnionFind {
constructor(n) {
this.parent = new Array(n).fill(0).map((item,index) => {
return index
})
this.size = new Array(n).fill(1)
// 当前连通数
this.result = n
}
/**
* @method find 进行路径压缩
* @param {Number} x 待查询的值
*/
find(x) {
if(this.parent[x] == x) return x;
this.parent[x] = this.find(this.parent[x])
return this.parent[x]
}
/**
* @method unite 进行合并
* @param {*} x
* @param {*} y
*/
unite(x, y) {
x = this.find(x)
y = this.find(y)
if(x == y) return
if(this.size[x] < this.size[y]) {
[x, y] = [y, x]
}
this.parent[y] = x
this.size[x] += this.size[y]
this.result --
}
}
var result = makeConnected(4, [[0,1],[0,2],[1,2]])
并查集比较适合用在 判断图的连通性,图的连通个数, 图是否存在环
这个是我最近学习并查集算法的写的一个工具函数,方便之后自己温习(j加油!!!!!!)