-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimizeMalwareSpreadII.cpp
More file actions
50 lines (46 loc) · 1.42 KB
/
minimizeMalwareSpreadII.cpp
File metadata and controls
50 lines (46 loc) · 1.42 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Source: https://leetcode.com/problems/minimize-malware-spread-ii/
// Author: Miao Zhang
// Date: 2021-03-26
class Solution {
public:
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
int n = graph.size();
vector<int> clean(n, 1);
for (auto& x: initial) {
clean[x] = 0;
}
vector<vector<int>> infected_by(n);
for (int& x: initial) {
set<int> seen;
dfs(graph, clean, x, seen);
for (int v: seen) {
infected_by[v].push_back(x);
}
}
vector<int> contribution(n);
for (int v = 0; v < n; v++) {
if (infected_by[v].size() == 1) {
contribution[infected_by[v][0]]++;
}
}
int res = *min_element(begin(initial), end(initial));
int resscore = -1;
for (int x: initial) {
int score = contribution[x];
if (score > resscore || score == resscore && x < res) {
res = x;
resscore = score;
}
}
return res;
}
private:
void dfs(vector<vector<int>>& graph, vector<int>& clean, int u, set<int>& seen) {
for (int v = 0; v < graph.size(); v++) {
if (graph[u][v] == 1 && clean[v] == 1 && !seen.count(v)) {
seen.insert(v);
dfs(graph, clean, v, seen);
}
}
}
};