Minimize Malware Spread

IF
AlgoAxiomStaff Engineers
JSTS
Hard20 mins

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, both nodes will be infected. This spread continues until no more nodes can be infected.

Suppose M(initial) is the final number of nodes infected in the entire network after the spread 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 the one with the smallest index.

Examples

Example 1:

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

Output: 0

Explanation: Removing node 0 or 1 prevents 2 nodes from being infected. Return the smaller index.

Example 2:

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

Output: 0

Explanation: Each infected node is in its own component of size 1. Both save equally, return smallest index.

Example 3:

Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]

Output: 1

Explanation: All nodes are connected. Removing any infected node still leaves the others infected. Return smallest index.

Constraints

  • n == graph.length == graph[i].length
  • 2 <= n <= 300
  • graph[i][j] is 0 or 1
  • graph[i][i] == 1
  • graph[i][j] == graph[j][i]
  • 1 <= initial.length <= n
  • 0 <= initial[i] <= n - 1
  • All values in initial are unique
Source: Union Find pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle