本题力扣传送门
这道题一样,并查集,其中的判断两个是否相连connected方法并没有用到,需要注意的是,最后返回的是getCount()-1;
/*
* @lc app=leetcode.cn id=1319 lang=javascript
*
*
*/
// @lc code=start
/**
* @param {number} n
* @param {number[][]} connections
* @return {number}
*/
var makeConnected = function (n, connections) {
if (connections.length < n - 1) {
return -1;
}
const uf = new UnionFind(n);
for (const con of connections) {
uf.unite(con[0], con[1])
}
return uf.getCount() - 1;
};
class UnionFind {
constructor(n) {
this.parent = new Array(n).fill(0).map((v, i) => i);
this.size = new Array(n).fill(1);
this.count = n;
}
find(index) {
let root = this.parent[index];
if (root != index) {
root = this.find(root)
}
return root
}
unite(index1, index2) {
let root1 = this.find(index1), root2 = this.find(index2)
if (root1 === root2) {
return;
}
if (root1 < root2) {
[root1, root2] = [root2, root1]
}
this.parent[root2] = root1;
this.size[root1] += this.size[root2];
this.count--;
}
getCount() {
return this.count;
}
connected(index1, index2) {
return this.find(index1) === this.find(index2)
}
}
// @lc code=end