924 Minimize Malware Spread¶
In a network of nodes, each node i is directly connected to another node j if and only 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 one node from the initial list. 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.
Note that if a node was removed from the initial list of infected nodes, it may still be infected later as a result of the malware spread.
Example 1:
Example 2:
Example 3:
Solution: BFS¶
Time complexity: \(O(n^3)\) Space complexity: \(O(n^2)\)
class Solution {
public:
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
int min_affected = INT_MAX;
int min_node = -1;
sort(begin(initial), end(initial));
for (int t : initial) {
vector<int> bad(graph.size(), 0);
queue<int> q;
for (int n : initial)
if (n != t) {
bad[n] = 1;
q.push(n);
}
int affected = initial.size() - 1;
while (!q.empty()) {
int size = q.size();
while (size--) {
int n = q.front(); q.pop();
for (int i = 0; i < graph[n].size(); ++i) {
if (graph[n][i] == 0 || bad[i]) continue;
++affected;
bad[i] = 1;
q.push(i);
}
}
}
if (affected < min_affected) {
min_affected = affected;
min_node = t;
}
}
return min_node;
}
};