## Algorithm

Problem Name: 928. Minimize Malware Spread II

You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` 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:

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

Example 2:

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

Example 3:

```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.

## Code Examples

### #1 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
const minMalwareSpread = function (graph, initial) {
const map = new Map(), n = graph.length
for(let init of initial) {
const visited = new Set(initial)
const q = [init]
while(q.length) {
const cur = q.pop()
for(let i = 0; i < n; i++) {
if(graph[cur][i] === 1 && !visited.has(i)) {
q.push(i)
if(map.get(i) == null) map.set(i, [])
map.get(i).push(init)
}
}
}
}

let res = 0, max = -1
const arr = Array(n)
for(let [k,v] of map) {
if(v.length === 1) {
if(arr[v] == null) arr[v] = 0
arr[v]++
}
}

for(let k = 0; k < n; k++) {
const v = arr[k]
if(v > max) {
max = v
res = +k
}
}

let min = Infinity
for(let e of initial) {
if(e < min) min = e
}
return max === -1 ? min: res

}
``````
Copy The Code &

Input

cmd
graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]

### #2 Code Example with Python Programming

```Code - Python Programming```

``````
class Solution:
def dfs(i):
return not any(graph[i][j] and j not in seen and (j in initials or not dfs(j)) for j in range(len(graph[i])))
res, mx, initials = min(initial), 1, set(initial)
for node in sorted(initial):
impact = set()
for j in range(len(graph[node])):
seen = {node}
if graph[node][j] and j not in initials and dfs(j): impact |= seen
if len(impact) > mx: res, mx = node, len(impact)
return res
``````
Copy The Code &

Input

cmd
graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]