You are given a network of n nodes represented as an n × n adjacency matrix graph, where the i-th node is directly connected to the j-th node if graph[i][j] == 1.

Some nodes in 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: If a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.

Input & Output

Example 1 — Basic Network
$ Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0
💡 Note: Nodes 0 and 1 are connected, so removing either still results in both getting infected. Node 2 is isolated. Since both removals give same result, return smaller index 0.
Example 2 — Unique Infection Source
$ Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,1]
Output: 0
💡 Note: Each node is isolated. Removing node 0 saves that component, removing node 1 saves its component. Both save 1 node, return smaller index 0.
Example 3 — Large Component
$ Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [0,1]
Output: 0
💡 Note: All nodes are connected. Removing either 0 or 1 still results in all 3 nodes infected via the remaining initial node. Return smaller index 0.

Constraints

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

Visualization

Tap to expand
Minimize Malware Spread: Network AnalysisOriginal Network012Initial: [0,1]After Spread012Infected: 2 nodesRemove Node 0012Result: 1 infectedRemove Node 1012Result: 1 infectedBoth give same result → Return smallest index: 0
Understanding the Visualization
1
Input Network
Graph with connections and initial infected nodes
2
Malware Spread
Infection spreads through connections
3
Optimal Removal
Find node removal that minimizes total infection
Key Takeaway
🎯 Key Insight: Find the initial node whose removal saves the most nodes from infection by analyzing connected components
Asked in
Google 25 Facebook 18 Amazon 12
28.4K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen