1319. Number of operations connected to the network
N with an Ethernet cable is connected to a computer network, computers are numbered from 0
to n-1
. Cable- connections
expressed, which connections[i] = [a, b]
is connected to the computer a
and b
.
Any computer in the network can directly or indirectly access any other computer in the same network through the network.
To give you the initial wiring of this computer network connections
, you can unplug the cable between any two directly connected computers and use it to connect a pair of computers that are not directly connected. Please calculate and return the minimum number of operations required to connect all computers. If it is not possible, return -1
.
Example 1:
输入:n = 4, connections = [[0,1],[0,2],[1,2]]
输出:1
解释:拔下计算机 1 和 2 之间的线缆,并将它插到计算机 1 和 3 上。
Example 2:
输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
输出:2
Example 3:
输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
输出:-1
解释:线缆数量不足。
Example 4:
输入:n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
输出:0
prompt:
- 1 <= n <= 10^5
- 1 <= connections.length <= min(n*(n-1)/2, 10^5)
- connections[i].length == 2
- 0 <= connections[i][0], connections[i][1] < n
- connections[i][0] != connections[i][1]
- There are no duplicate connections.
- Two computers will not be connected by multiple cables.
Method 1: Collect and check
It is still a problem of connectivity. Use "Union Check and Set".
Problem-solving ideas
- Connected
n
machines, requires a minimum ofn - 1
lines, the first line is determined enough. - If there are enough lines, use "Combine Check and Set" to merge the machines.
- Find the "disjoint-set" There are several individual
分区
,分区数 - 1
that is, the number of operations needed (as in Example 2: A total of3
partitions needed2
operations)
Reference Code
public int makeConnected(int n, int[][] connections) {
int len = connections.length;
if (n > len + 1) {
return -1;
}
UnionFind unionFind = new UnionFind(n);
for (int[] conn : connections) {
unionFind.union(conn[0], conn[1]);
}
int parent = 0;
for (int i = 0; i < n; i++) {
if (unionFind.panret[i] == i) {
parent += 1;
}
}
return parent - 1;
}
class UnionFind {
private int[] panret;
public UnionFind(int n) {
panret = new int[n];
for (int i = 0; i < n; i++) {
panret[i] = i;
}
}
public void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) {
return;
}
panret[rootX] = rootY;
}
public int find(int x) {
return panret[x] == x ? panret[x] : (panret[x] = find(panret[x]));
}
}
Results of the