LeetCode 924 Minimize Malware Spread

Problem Statement

For each initially infected node, try remove it and then count the total number of infected nodes through BFS.
Pick up the solution that if removing such a node will yield the minimum number of infected nodes.


use std::vec::Vec;
use std::collections::VecDeque;

impl Solution {
pub fn min_malware_spread(graph: Vec<Vec<i32>>, initial: Vec<i32>) -> i32 {
let (mut ans, mut min) = (-1, 400);
let mut input = initial;
input.sort();

for t in &input {
let mut bad = vec![0; graph.len()];
let mut q = VecDeque::new();
for n in &input {
if *n == *t {
continue;
}
bad[*n as usize] = 1; q.push_back(*n as usize);
}

let mut affected = input.len() - 1;
while !q.is_empty() {
let n = q.pop_front().unwrap();
for (i, item) in graph[n].iter().enumerate() {
if bad[i as usize] == 1 || *item == 0 {
continue;
}
affected += 1; bad[i as usize] = 1; q.push_back(i as usize);
}
}

if affected < min {
min = affected;
ans = *t;
}
}

return ans;
}
}