Number of Operations to Make Network Connected
Move spare cables so every computer joins one network, by counting the separate groups of computers.
There are nconnectionsconnections[i] = [a, b]ab
Example 1
Output: 1
Explanation: move cable 1 - 2 so that it joins computer 3 to the others.
Example 2
Output: 2
Example 3
Output: -1
Explanation: 4 cables cannot connect 6 computers.
The Idea
Picture an office where some computers are wired together and a few sit on their own. There is no new cable to buy. All you can do is unplug a cable from one place and plug it in somewhere else, and you want everyone on one network in as few moves as possible.
Look at the left half of the picture below, which is Example 2. Computers 0, 1, 2 and 3 are wired together, while computers 4 and 5 have no cable at all. Computers that can reach each other, directly or through a chain of cables, form a group. The left half shows three groups, each in its own dashed box: {0, 1, 2, 3}, {4} and {5}. In graph terms, the computers are vertices, the cables are edges, and a group is called a connected component.
Which cables can we take away without cutting anyone off? Inside the big group, computer 0 already reaches 1, 2 and 3 through the blue cables 0 - 1, 0 - 2 and 0 - 3. The orange cables, 1 - 2 and 1 - 3, join computers that could already talk through 0. Unplugging either one leaves the group whole, so the picture labels them "spare cables".
Each moved cable can join two groups into one. Three groups need two such joins, and the right half of the picture shows them: the spare cables now run 3 - 4 and 3 - 5, and all six computers form 1 group. That is the answer 2.
Example 3 has the same three groups but one cable fewer. Only 1 - 2 is spare now, so after one move computer 5 is still alone. Could there be too few spare cables even when there are enough cables in total to join every computer? If that never happens, the whole problem comes down to one count: the number of groups.
Solution Approach
Turning that idea into code means settling three things: when the answer is -1, whether there are always enough spare cables otherwise, and how to count the groups. A second way to count the groups, a search that follows the cables, is an option.
When there are too few cables
How many cables does it take to join nnn
Counting spare cables
With at least n - 1 cables, are there always enough spare ones? Call the number of groups g
Every other cable is spare. With at least n - 1 cables in total, the spare ones number at least (n - 1) - (n - g) = g - 1, which is exactly the number of moves needed. So once the cable check passes, the answer is simply g - 1, and the spare cables never have to be found or counted.
Counting groups with union-find
How do we count the groups? Give each computer a parent, another computer it points to. Following parents from any computer ends at one computer that points to itself, the root, and that root names the computer's group. At the start every computer is its own root, so there are n
Now go through the cables one by one and find the root of each end. Different roots mean the cable joins two groups: point one root at the other, and the count drops by one. The same root means the cable is spare. In Example 2, cables 0 - 1, 0 - 2 and 0 - 3 each join two groups, taking the count from 6 to 3. Cables 1 - 2 and 1 - 3 find the same root at both ends, so the count stays 3.
Finding a root walks up a chain of parents, and chains could grow long. While walking, each computer can be pointed at its parent's parent, which halves the chain for the next walk. Pointing at the grandparent like this is called path halving, and the whole structure of parents, roots and merging is called union-find, or a disjoint set.
Optional: counting groups with a depth-first search
The groups can also be counted by walking the cables. First turn the cable list into an adjacency list: for each computer, the list of computers it has a cable to. For Example 2 that is 0: [1, 2, 3], 1: [0, 2, 3], 2: [0, 1], 3: [0, 1], 4: [] and 5: [].
Then start at each computer that has not been visited yet and follow cables as far as they lead, marking every computer reached. Following one cable as deep as possible before backing up is called a depth-first search (DFS). In Example 2 the searches start at 0, 4 and 5, three starts for three groups. It gives the same answer, but needs the adjacency list as extra memory, so the code below uses union-find.
Java Solution
The method makeConnected
- First, compare the number of cables,
, with n - 1. With fewer cables, return -1 straight away.connections.length - Create the array
, one entry per computer, and fill it in a loop so thatparent : every computer is its own root. Setparent[i] = i togroups .n - Loop over the cables. For each
, call the helpercable on both ends to get their roots,find anda . Insideb , a loop follows parents until it reaches a computer that is its own parent, pointing each computer it passes at its grandparent on the way.find - If
anda differ, setb to merge the two groups and lowerparent[a] = b by one. If they are equal, the cable is spare and nothing changes.groups - After the loop, return
, the number of cables to move.groups - 1
The main
public class NumberOfOperationsToMakeNetworkConnected {
public static int makeConnected(int n, int[][] connections) {
if (connections.length < n - 1) {
return -1; // too few cables, however they are moved
}
int[] parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i; // every computer starts as its own group
}
int groups = n;
for (int[] cable : connections) {
int a = find(parent, cable[0]);
int b = find(parent, cable[1]);
if (a != b) {
parent[a] = b; // the cable joins two groups into one
groups--;
} // else: a spare cable inside one group
}
return groups - 1; // one moved cable joins two groups
}
private static int find(int[] parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // path halving: skip one level
x = parent[x];
}
return x;
}
public static void main(String[] args) {
System.out.println(makeConnected(4, new int[][] {{0, 1}, {0, 2}, {1, 2}}));
System.out.println(makeConnected(6,
new int[][] {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}}));
System.out.println(makeConnected(6, new int[][] {{0, 1}, {0, 2}, {0, 3}, {1, 2}}));
System.out.println(makeConnected(3, new int[][] {{0, 1}, {1, 2}}));
System.out.println(makeConnected(1, new int[][] {}));
System.out.println(makeConnected(5,
new int[][] {{0, 1}, {1, 2}, {2, 0}, {3, 4}}));
}
}
Running it prints:
1
2
-1
0
0
1
The values 1, 2 and -1 at the top match Examples 1, 2 and 3. The two 0 lines are networks that need no moves. The chain 0 - 1 - 2 is already one group, and a single computer with no cables passes the check, because it needs n - 1 = 0 cables.
Look at the last line, 1. Cables 0 - 1 and 1 - 2 join computers 0, 1 and 2, so cable 2 - 0 finds the same root at both ends and is spare. Cable 3 - 4 forms the second group, and moving 2 - 0 joins the two.
The cable check at the start matters even though the loop never looks for spare cables. Without it, Example 3 returns 2, because its three groups would ask for two moves while only cable 1 - 2 is spare.
Complexity
The work is filling parentfind
- Time: O(n + E log n), where E is the number of cables, because filling
takes n steps and path halving keeps each of the 2Eparent calls at O(log n) steps when averaged over all the calls.find - Space: O(n), because
holds one entry per computer andparent is a loop rather than a method calling itself, so it adds nothing on the call stack.find
The same union-find setup decides