AlgoMaster Logo

Minimize Malware Spread

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. DFS for Component Identification

Intuition:

The problem is essentially about identifying connected components in a graph and determining the effect of removing a malware-infected node. We can use Depth First Search (DFS) to identify the size of each connected component and keep track of nodes that are initially infected.

  1. First, mark all connected nodes using DFS for each unvisited node, which helps identify components.
  2. For each initially infected node, simulate its removal and determine how many other nodes can be saved by using the largest saved component strategy.

Algorithm:

  1. Traverse the graph using DFS to identify components and their sizes.
  2. Record infected nodes within these components.
  3. Evaluate each infected node's removal impact. If multiple nodes result in the same number of saved nodes, choose the node with the smallest index.

Code:

2. Union Find (Disjoint Set)

Intuition:

A more efficient approach than DFS is using a Union Find (Disjoint Set) data structure to determine connected components. This method efficiently merges nodes and provides component size information.

  1. Use Union-Find to identify connected components.
  2. Count infected nodes within each component.
  3. By eliminating a node that is the only infected node within a component, maximize saved nodes.

Algorithm:

  1. Implement Union-Find to determine component connections.
  2. Count the infected nodes in each component.
  3. Identify the node whose removal saves the maximum nodes.

Code: