Problem Description
Given an undirected graph represented as an n x n adjacency matrix, some nodes are initially infected by malware. When any infected node is connected to another node, the infection spreads over the connection. You are allowed to remove exactly one node from the initial infected list—this removal deletes the node and all of its connections. The task is to choose a node to remove such that after the malware spread stops, the total number of infected nodes is minimized. In case of multiple optimal answers, return the node with the smallest index.
Key Insights
- Removing one infected node not only prevents its own infection but also may protect other nodes by breaking infection paths.
- The spread can be simulated by starting from each remaining infected node (after removal) and propagating using either BFS or DFS.
- Although advanced union-find or component-based solutions exist, simulating the infection process for each candidate removal is feasible given n <= 300.
- For each candidate removal, the simulation ignores the removed node completely (both as an infection source and as a neighbor).
Space and Time Complexity
Time Complexity: O(k * n^2) where k is the number of nodes in the initial list (k < n) and n is the number of nodes. In worst-case, this is roughly O(n^3) but acceptable for n up to 300. Space Complexity: O(n) for storing the visited/infected status during simulation.
Solution
We iterate through each node in the initial infected list and simulate the spread of malware after removing that node. For each simulation, we:
- Mark the removed candidate as “removed” (i.e., it is not considered in the spread).
- Start a BFS/DFS from every remaining initially infected node (skipping the removed one) to compute the final set of infected nodes.
- Count how many nodes become infected.
- Compare the result to find the candidate removal that minimizes the infection count. In the case of a tie, we select the candidate with the smallest index. This simulation approach uses a graph traversal algorithm (BFS/DFS) for each candidate removal.