#1319
Medium Algorithms Number of operations to make network connected
Depth-First Search Breadth-First Search Union-Find Graph Theory
66.2% acceptance
Feb 25, 2026
5570
83
There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.
Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn make_connected(n: i32, connections: Vec<Vec<i32>>) -> i32 {
let n = n as usize;
if connections.len() < n - 1 { return -1; }
let mut parent: Vec<usize> = (0..n).collect();
let mut rank = vec![0usize; n];
fn find(parent: &mut Vec<usize>, x: usize) -> usize {
if parent[x] != x { parent[x] = find(parent, parent[x]); }
parent[x]
}
let mut components = n;
for conn in &connections {
let (a, b) = (conn[0] as usize, conn[1] as usize);
let (pa, pb) = (find(&mut parent, a), find(&mut parent, b));
if pa != pb {
if rank[pa] < rank[pb] { parent[pa] = pb; }
else if rank[pa] > rank[pb] { parent[pb] = pa; }
else { parent[pb] = pa; rank[pa] += 1; }
components -= 1;
}
}
(components - 1) as i32
}
}