#928
Hard Algorithms Minimize malware spread ii
Array Hash Table Depth-First Search Breadth-First Search Union-Find Graph Theory
45.5% acceptance
Feb 25, 2026
708
92
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.
Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops.
We will remove exactly one node from initial, completely removing it and any connections from this node to any other node.
Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.
Solution
Rust
Time O(n³)
Space O(n)
impl Solution {
pub fn min_malware_spread(graph: Vec<Vec<i32>>, initial: Vec<i32>) -> i32 {
let n = graph.len();
let initial_set: std::collections::HashSet<usize> = initial.iter().map(|&x| x as usize).collect();
let mut initial_sorted = initial.clone();
initial_sorted.sort();
// For each initial node, BFS from all other initial nodes (excluding this one)
// Count how many non-initial nodes get infected
let mut best = initial_sorted[0];
let mut best_save = -1i32;
for &remove in &initial_sorted {
let remove = remove as usize;
let mut infected = vec![false; n];
let mut queue = std::collections::VecDeque::new();
for &src in &initial_set {
if src != remove && !infected[src] {
infected[src] = true;
queue.push_back(src);
}
}
while let Some(node) = queue.pop_front() {
for nb in 0..n {
if nb != remove && graph[node][nb] == 1 && !infected[nb] {
infected[nb] = true;
queue.push_back(nb);
}
}
}
// Count infected non-initial nodes if we remove 'remove'
// We want to minimize M(initial) = minimize infected count
let total_infected: i32 = infected.iter().filter(|&&x| x).count() as i32;
if total_infected < best_save || best_save == -1 {
best_save = total_infected;
best = remove as i32;
}
}
best
}
}