[LeetCode] Number of Operations to Make Network Connected

1319. Number of Operations to Make Network Connected

There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.

You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.

Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.

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
class Solution {
vector<int> g;
int find(int n) {
return g[n] == n ? n : g[n] = find(g[n]);
}
void uni(int a, int b) {
int pa = find(a), pb = find(b);
g[pa] = g[pb] = min(pa, pb);
}
public:
int makeConnected(int n, vector<vector<int>>& connections) {
if(connections.size() < n - 1) return -1;
g = vector<int>(n);
for(int i = 0; i < n; i++) g[i] = i;

for(auto conn : connections) {
uni(conn[0], conn[1]);
}

unordered_set<int> s;
for(int i = 0; i < n; i++) {
s.insert(find(i));
}
return s.size() - 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/04/PS/LeetCode/number-of-operations-to-make-network-connected/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.