Sponsored
Sponsored
This approach uses the Union-Find (or Disjoint Set Union, DSU) data structure. It helps in efficiently finding the number of connected components in the network. Initially, every computer is its own component. We then iterate over each connection and unite the components of the two connected computers. Finally, we count how many separate components remain, since that will determine the number of cables needed to connect them.
Time Complexity: O(n + c), where n is the number of computers and c is the number of connections. Essentially, this is equivalent to O(c) given c > n. Space Complexity: O(n) for storing parent and rank arrays.
1public class Solution {
2 public int MakeConnected(int n, int[][] connections) {
3 if (connections.Length < n - 1) return -1;
4
5 int[] parent = new int[n];
6 int[] rank = new int[n];
7 for (int i = 0; i < n; i++) parent[i] = i;
8
9 foreach (var conn in connections) {
10 Union(parent, rank, conn[0], conn[1]);
11 }
12
13 int components = 0;
14 for (int i = 0; i < n; i++) {
if (Find(parent, i) == i) components++;
}
return components - 1;
}
private int Find(int[] parent, int i) {
if (parent[i] != i) {
parent[i] = Find(parent, parent[i]);
}
return parent[i];
}
private void Union(int[] parent, int[] rank, int x, int y) {
int rootX = Find(parent, x);
int rootY = Find(parent, y);
if (rootX != rootY) {
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
}
The C# solution implements a Union-Find structure with helper methods for finding with path compression and uniting with rank balancing. By identifying the sets of independent components, we calculate the number of necessary operations to form a single network.
In this approach, we consider the computers and connections as a graph and use Depth-First Search (DFS) to determine the number of connected components. If there are at least n - 1 connections, it is possible to make the computers connected; otherwise, it isn't. Once the number of connected components is known, the number of operations required is the number of components minus one.
Time Complexity: O(n + c), where n is the number of computers and c is the connections. Space Complexity: O(n), managing the graph and visited structure.
In the Java solution, we transform the network into a graph structure using an adjacency list. The DFS function traverses each connected component, and the main function counts these connected sections, returning the total connections minus one.