# 924. Minimize Malware Spread

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. `1 < graph.length = graph[0].length <= 300`
2. `0 <= graph[i][j] == graph[j][i] <= 1`
3. `graph[i][i] = 1`
4. `1 <= initial.length < graph.length`
5. `0 <= initial[i] < graph.length`

```cpp
int findRoot(vector<int>& roots, int i) {
    return roots[i] == i ? i : roots[i] = findRoot(roots, roots[i]);
}
void quickUnion(vector<int>& roots, vector<int>& size, int i, int j) {
    int p = findRoot(roots, i), q = findRoot(roots, j);
    if (p == q) return;
    if (size[p] < size[q]) {
        roots[p] = q;
        size[q] += size[p];
    } else {
        roots[q] = p;
        size[p] += size[q];
    }
}
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) { // time: O(n^2 * log*(n)); space: O(n)
    int n = graph.size();
    vector<int> roots(n, 0), size(n, 1), malCnt(n, 0);
    
    // Initialize roots array
    for (int i = 0; i < n; ++i) roots[i] = i;
    
    // Union nodes based on graph
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            if (graph[i][j]) quickUnion(roots, size, i, j);
        }
    }
    
    // Count malware 
    for (int init : initial) {
        ++malCnt[findRoot(roots, init)];
    }
    
    // vector<int> res = {1, 0};
    // for (int i : initial)
    //     res = min(res, {(malCnt[findRoot(roots, i)] == 1 ) * (-size[findRoot(roots, i)]), i});
    // return res[1];
    
    int res = -1, maxSize = 0;
    sort(initial.begin(), initial.end());
    for (int i : initial) {
        int r_i = findRoot(roots, i);
        if (malCnt[r_i] == 1 && size[r_i] > maxSize) {
            maxSize = size[r_i];
            res = i;
        }
    }
    if (maxSize != 0) return res;
    else return initial[0];
}
```
