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 c o n n e c t i o n s i = a i , b i connectionsi = a_i, b_i connectionsi=ai,bi represents a connection between computers a i a_i ai and b i b_i 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.
Example 1:

Input: n = 4, connections = \[0,1,0,2,1,2]
Output: 1
Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.
Example 2:

Input: n = 6, connections = \[0,1,0,2,0,3,1,2,1,3]
Output: 2
Example 3:
Input: n = 6, connections = \[0,1,0,2,0,3,1,2]
Output: -1
Explanation: There are not enough cables.
Constraints:
- 1 < = n < = 10 5 1 <= n <= 10^5 1<=n<=105
- 1 <= connections.length <= m i n ( n ∗ ( n − 1 ) / 2 , 10 5 ) min(n * (n - 1) / 2, 10^5) min(n∗(n−1)/2,105)
- connectionsi.length == 2
- 0 < = a i , b i < n 0 <= a_i, b_i < n 0<=ai,bi<n
- a i ! = b i a_i != b_i ai!=bi
- There are no repeated connections.
- No two computers are connected by more than one cable.
From: LeetCode
Link: 1319. Number of Operations to Make Network Connected
Solution:
Ideas:
Union-Find groups computers that are already connected.
- Initially, every computer is its own component.
- Each successful union reduces the number of components by one.
- If there are k separate components, exactly k - 1 cable moves are required.
- A connected network with n computers requires at least n - 1 cables.
Code:
c
#include <stdlib.h>
static int findRoot(int* parent, int x) {
if (parent[x] != x) {
parent[x] = findRoot(parent, parent[x]);
}
return parent[x];
}
static int unionSets(int* parent, int* rank, int a, int b) {
int rootA = findRoot(parent, a);
int rootB = findRoot(parent, b);
if (rootA == rootB) {
return 0;
}
if (rank[rootA] < rank[rootB]) {
parent[rootA] = rootB;
} else if (rank[rootA] > rank[rootB]) {
parent[rootB] = rootA;
} else {
parent[rootB] = rootA;
rank[rootA]++;
}
return 1;
}
int makeConnected(int n, int** connections, int connectionsSize,
int* connectionsColSize) {
(void)connectionsColSize;
/* At least n - 1 cables are required. */
if (connectionsSize < n - 1) {
return -1;
}
int* parent = malloc(n * sizeof(int));
int* rank = calloc(n, sizeof(int));
if (parent == NULL || rank == NULL) {
free(parent);
free(rank);
return -1;
}
for (int i = 0; i < n; i++) {
parent[i] = i;
}
int components = n;
for (int i = 0; i < connectionsSize; i++) {
int a = connections[i][0];
int b = connections[i][1];
if (unionSets(parent, rank, a, b)) {
components--;
}
}
free(parent);
free(rank);
return components - 1;
}