## Description

LeetCode Problem 924.

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.

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 might still be infected later due to the malware spread.

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,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0
``````

Example 3:

``````1
2
Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
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.

## Sample C++ Code using Union Find

``````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
class Solution {
public:
vector<int> parents;
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
int n = graph.size();
for (int i = 0; i < n; ++i)
parents.push_back(i);
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
if (graph[i][j]) uni(i, j);
vector<int> area(n, 0), malware(n, 0);
for (int i = 0; i < n; ++i)
area[find(i)]++;
for (int i : initial)
malware[find(i)]++;
vector<int> res = {1, 0};
for (int i : initial)
res = min(res, {(malware[find(i)] == 1 ) * (-area[find(i)]), i});
return res;
}

int find(int x) {
if (x != parents[x])
parents[x] = find(parents[x]);
return parents[x];
}
void uni(int x, int y) {
parents[find(x)] = find(y);
}
};
``````