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.
The key idea is to count the number of connected components in the network. To connect all computers, we need at least n-1 cables. If there are enough cables, the answer is the number of components minus one (the number of operations needed to connect all components).
classSolution {
publicintmakeConnected(int n, int[][] connections) {
if (connections.length< n - 1) return-1;
int[] par =newint[n];
for (int i = 0; i < n; i++) par[i]= i;
java.util.function.IntUnaryOperator find =new java.util.function.IntUnaryOperator() {
publicintapplyAsInt(int x) { return par[x]== x ? x : (par[x]= applyAsInt(par[x])); }
};
for (int[] e : connections) par[find.applyAsInt(e[0])]= find.applyAsInt(e[1]);
int comp = 0;
for (int i = 0; i < n; i++) if (find.applyAsInt(i) == i) comp++;
return comp - 1;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funmakeConnected(n: Int, connections: Array<IntArray>): Int {
if (connections.size < n - 1) return -1val par = IntArray(n) { it }
funfind(x: Int): Int = if (par[x] == x) x else { par[x] = find(par[x]); par[x] }
for (e in connections) par[find(e[0])] = find(e[1])
var comp = 0for (i in0 until n) if (find(i) == i) comp++return comp - 1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defmakeConnected(self, n: int, connections: list[list[int]]) -> int:
if len(connections) < n -1:
return-1 par = list(range(n))
deffind(x):
if par[x] != x:
par[x] = find(par[x])
return par[x]
for u, v in connections:
par[find(u)] = find(v)
comp = sum(find(i) == i for i in range(n))
return comp -1