-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path1319.连通网络的操作次数.js
52 lines (47 loc) · 1.29 KB
/
1319.连通网络的操作次数.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* 1. 使用并查集统计连通集合, 0 表示独立点, 1 ~ n 表示集合, 数值相同则在同一集合
* 2. n 个集合需要 n - 1 条线连接起来
* 3. m 个独立的点 需要 m 条线连接起来
*/
/**
* @param {number} n
* @param {number[][]} connections
* @return {number}
*/
var makeConnected = function(n, connections) {
if (connections.length < n - 1) {
return -1;
}
let union = new Array(n).fill(0);
let current = 1;
for (const [a, b] of connections) {
if (union[a] === 0 && union[b] === 0) {
union[a] = union[b] = current;
current++;
} else {
if (union[a] === 0) {
union[a] = union[b];
} else if (union[b] === 0) {
union[b] = union[a];
} else {
const v = union[b];
union[b] = union[a];
for (let i = 0; i < union.length; i++) {
if (union[i] === v) {
union[i] = union[a];
}
}
}
}
}
let result = 0;
const set = new Set();
for (const n of union) {
if (n === 0) {
result++;
} else {
set.add(n);
}
}
return result + set.size - 1;
};