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; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment