Number of Operations to Make Network Connected
There are n computers numbered 0 to n-1 connected by ethernet cables; connections[i] = [a, b] means computers a and b are directly connected. You may unplug any existing cable and plug it between any two computers. Return the minimum number of such moves to make every computer connected to every other (one single network), or -1 if it is impossible.
Open official problem prompt ↗Find the fewest cable relocations that turn a partially connected set of computers into one fully connected network, or prove it cannot be done.
Think of islands joined by bridges. If you already have enough bridge material, every extra bridge inside an island can be lifted and dropped between two islands; you need exactly one relocation per gap between separate island groups.
- Input
- n = 4, connections = [[0,1],[0,2],[1,2]]
- Output
- 1
- Why
- Computers 0,1,2 are already one component and computer 3 is alone; one of the three cables among {0,1,2} is redundant and can be moved to link computer 3.
1 <= n <= 10^51 <= connections.length <= min(n*(n-1)/2, 10^5)connections[i].length == 20 <= a_i, b_i < na_i != b_iThere are no repeated connectionsNo two computers are connected by more than one cable