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.
1class 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 for (int[] conn : connections) {
10 union(parent, rank, conn[0], conn[1]);
11 }
12
13 int components = 0;
14 for (int i = 0; i < n; ++i) {
15 if (find(parent, i) == i) components++;
16 }
17
18 return components - 1;
19 }
20
21 private int find(int[] parent, int i) {
22 if (parent[i] != i) {
23 parent[i] = find(parent, parent[i]);
24 }
25 return parent[i];
26 }
27
28 private void union(int[] parent, int[] rank, int x, int y) {
29 int rootX = find(parent, x);
30 int rootY = find(parent, y);
31 if (rootX != rootY) {
32 if (rank[rootX] < rank[rootY])
33 parent[rootX] = rootY;
34 else if (rank[rootX] > rank[rootY])
35 parent[rootY] = rootX;
36 else {
37 parent[rootY] = rootX;
38 rank[rootX]++;
39 }
40 }
41 }
42}
In Java, the solution applies the Union-Find technique with two helper methods: find and union. Find ensures path compression, while union keeps the tree flat by rank. We compute the number of components and subtract one to get the minimum number of operations required.
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.
This C code defines a DFS approach to identify connected components in a graph. The graph is built using an adjacency list representation, and DFS traverses through unvisited nodes to explore connected nodes. The number of traversals gives the number of connected components, and we calculate required operations by subtracting one.