# Minimize Malware Spread II Problem

## Description

LeetCode Problem 928.

You are given a network of n nodes represented as an n x n adjacency matrix graph, where the i^th node is directly connected to the j^th node 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 exactly one node from initial, completely removing it and any connections from this node to any other node.

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.

Example 1:

``````1
2
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0
``````

Example 2:

``````1
2
Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
Output: 1
``````

Example 3:

``````1
2
Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
Output: 1
``````

Constraints:

• n == graph.length
• n == graph[i].length
• 2 <= n <= 300
• graph[i][j] is 0 or 1.
• graph[i][j] == graph[j][i]
• graph[i][i] == 1
• 1 <= initial.length < n
• 0 <= initial[i] <= n - 1
• All the integers in initial are unique.

``````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
class Solution {
public:
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
int n = graph.size();
unordered_map<int,vector<int>> count;
vector<bool> is_infected(n);
for (int &u : initial)
is_infected[u] = 1;
for (int &u : initial) {
vector<bool> visited(n);
queue<int> q;
q.push(u);
while (q.size()) {
int v = q.front();
q.pop();
for (int i = 0; i < n; i++) {
if (graph[v][i] == 0 or visited[i] or is_infected[i])
continue;
visited[i] = 1;
count[i].push_back(u);
q.push(i);
}
}
}
vector<int> ans(n);
for (auto &[u,arr] : count) {
if (arr.size() == 1)
ans[arr.front()]++;
}
int mxm = *max_element(ans.begin(), ans.end());
if (mxm == 0) {
return *min_element(initial.begin(), initial.end());
}
return find(ans.begin(), ans.end(), mxm) - ans.begin();
}
};
``````