Skip to content

928. Minimize Malware Spread II

Description

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.

 

Solutions

Solution: Breadth-First Search

  • Time complexity: O(n2 * initial.length)
  • Space complexity: O(n)

 

JavaScript

js
/**
 * @param {number[][]} graph
 * @param {number[]} initial
 * @return {number}
 */
const minMalwareSpread = function (graph, initial) {
  const n = graph.length;
  let result = n;
  let minInfected = Number.MAX_SAFE_INTEGER;

  const getInfectedCount = deleteNode => {
    const visited = new Array(n).fill(false);
    let queue = initial.filter(node => node !== deleteNode);
    let count = queue.length;

    for (const node of initial) visited[node] = true;

    while (queue.length) {
      const nextQueue = [];

      for (const node of queue) {
        for (let neighbor = 0; neighbor < n; neighbor++) {
          if (visited[neighbor]) continue;
          const isConnected = graph[node][neighbor];

          if (!isConnected) continue;
          nextQueue.push(neighbor);
          visited[neighbor] = true;
          count += 1;
        }
      }
      queue = nextQueue;
    }
    return count;
  };

  initial.sort((a, b) => a - b);

  for (const node of initial) {
    const count = getInfectedCount(node);

    if (count >= minInfected) continue;
    result = node;
    minInfected = count;
  }
  return result;
};

Released under the MIT license