Problem
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:
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0
Example 2:
Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0
Example 3:
Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1
Note:
1 < graph.length = graph[0].length <= 300
0 <= graph[i][j] == graph[j][i] <= 1
graph[i][i] = 1
1 <= initial.length < graph.length
0 <= initial[i] < graph.length
Solution: BFS
Time complexity: O(n^3)
Space complexity: O(n^2)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// Author: Huahua 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; } }; |