-
Notifications
You must be signed in to change notification settings - Fork 0
/
1319. Number of Operations to Make Network Connected
71 lines (53 loc) · 1.45 KB
/
1319. Number of Operations to Make Network Connected
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class Solution {
public int makeConnected(int n, int[][] connections) {
if (connections.length < n - 1) {
return -1;
}
UnionFind uf = new UnionFind(n);
for (int[] connection : connections) {
uf.union(connection[0], connection[1]);
}
int numComponents = uf.getCount();
return numComponents - 1;
}
class UnionFind {
private int[] parent;
private int[] rank;
private int count;
public UnionFind(int size) {
parent = new int[size];
rank = new int[size];
count = size;
for (int i = 0; i < size; i++) {
parent[i] = i;
rank[i] = 1;
}
}
public int find(int p) {
if (parent[p] != p) {
parent[p] = find(parent[p]);
}
return parent[p];
}
public boolean union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) {
return false;
}
if (rank[rootP] > rank[rootQ]) {
parent[rootQ] = rootP;
} else if (rank[rootP] < rank[rootQ]) {
parent[rootP] = rootQ;
} else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
return true;
}
public int getCount() {
return count;
}
}
}