leetcode 1319. 连通网络的操作次数
问题描述: 用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0 到 n-1。线缆用 connections 表示,其中 connections[i] = [a, b] 连接了计算机 a 和 b。
网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。
给你这个计算机网络的初始布线 connections,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。
示例 1:
输入: n = 4, connections = [[0,1],[0,2],[1,2]]
输出: 1
解释: 拔下计算机 1 和 2 之间的线缆,并将它插到计算机 1 和 3 上。
思路: 并查集:先根据参数,把连接的电脑分为并查集,然后算出有多少个集合,也就算出了操作次数(res-1)
/**
* @param {number} n
* @param {number[][]} connections
* @return {number}
*/
var makeConnected = function(n, connections) {
let union=new unionSize(n);
if(connections.length<n-1)return -1;
for(let i=0;i<connections.length;i++){
if(union.find(connections[i][0])!==union.find(connections[i][1])) union.merge(union.find(connections[i][0]),union.find(connections[i][1]));
}
let res=0;
for(let i=0;i<union.node.length;i++){
if(i==union.find(i))res++
}
return res-1
};
class unionSize{
constructor(n){
this.node=new Array(n).fill(0).map((item,index)=>index);
}
find(x){
return this.node[x]=(x===this.node[x]?x:this.find(this.node[x]))
}
merge(x,y){
let fa=this.find(x),fb=this.find(y);
this.node[fa]=fb;
}
}