-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1319_Number_of_Operations_to_Make_Network_Connected.java
63 lines (48 loc) · 1.32 KB
/
1319_Number_of_Operations_to_Make_Network_Connected.java
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
/*
* 1319. Number of Operations to Make Network Connected
* Problem Link: https://leetcode.com/problems/number-of-operations-to-make-network-connected/
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class UnionFind {
int [] par;
int setCount = 0;
UnionFind(int n) {
par = new int[n];
for (int i = 0; i < n; i++) {
par[i] = i;
}
setCount = n;
}
int find(int x) {
if (par[x] == x) return x;
return par[x] = find(par[x]);
}
void union(int x, int y) {
x = find(x);
y = find(y);
if (x != y) {
par[x] =y;
setCount--;
}
}
}
class Solution {
public int makeConnected(int n, int[][] connections) {
// to connect n computers we need n-1 cables;
if (connections.length < n-1) {
return -1;
}
UnionFind uf = new UnionFind(n);
for (int [] connection: connections) {
uf.union(connection[0], connection[1]);
}
// number of operations will be equal to setCount -1 ;
// if 1 set, 0 operations, etc...
return uf.setCount - 1;
}
}