Graphs Union-find
463. Number of Operations to Make Network Connected
You have n computers, numbered from 0 to n - 1. Each pair [a, b] in connections is a cable that
joins computers a and b directly.
A network is a group of computers in which every computer can reach every other one through cables, and that no cable joins to a computer outside the group. A computer with no cable is a network on its own.
In one move, you unplug any cable and plug it in again between two computers that have no cable between
them. You cannot add new cables. Return the fewest moves that put all n computers in one network. If
that cannot be done, return -1.
Example 1
Input: n = 8
connections = [[0, 1],
[1, 2],
[2, 0],
[3, 4],
[4, 5],
[5, 3],
[2, 3]]
2Explanation: Computers 0 to 5 form one network, and computers 6 and 7 are networks on their own. One move takes
[2,0] to join 0 and 6, since 0 and 2 stay joined through 1. A second move takes [5,3] to join 3
and 7.
Example 2
Input: n = 5, connections = [[0, 1], [1, 2], [2, 0]]
-1Explanation: Joining 5 computers takes at least 4 cables, and there are only 3.
Example 3
Input: n = 4, connections = [[3, 0], [0, 2], [2, 1]]
0Explanation: The cables already join all four computers, so no move is needed.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ connections.length ≤ 2 × 105connections[i].length == 20 ≤ ai, bi < nai ≠ bi- No cable appears twice:
[a, b]and[b, a]are the same cable.
Clarifying questions
What you would ask an interviewer before writing any code.