Skip to content

928. Minimize Malware Spread II 👍

  • Time: $O(n^2 \cdot |\texttt{initial}|)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
 public:
  int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
    int ans = 0;
    int minCount = graph.size();

    ranges::sort(initial);

    for (const int i : initial) {
      const int count = bfs(graph, i, initial);
      if (count < minCount) {
        minCount = count;
        ans = i;
      }
    }

    return ans;
  }

 private:
  int bfs(const vector<vector<int>>& graph, int removed, vector<int>& initial) {
    queue<int> q;
    vector<bool> seen(graph.size());
    seen[removed] = true;

    int count = 0;

    for (const int i : initial)
      if (i != removed) {
        q.push(i);
        seen[i] = true;
      }

    while (!q.empty()) {
      const int u = q.front();
      q.pop();
      ++count;
      for (int i = 0; i < graph.size(); ++i) {
        if (seen[i])
          continue;
        if (i != u && graph[i][u]) {
          q.push(i);
          seen[i] = true;
        }
      }
    }

    return count;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
  public int minMalwareSpread(int[][] graph, int[] initial) {
    int ans = 0;
    int minCount = graph.length;

    Arrays.sort(initial);

    for (final int i : initial) {
      final int count = bfs(graph, i, initial);
      if (count < minCount) {
        minCount = count;
        ans = i;
      }
    }

    return ans;
  }

  private int bfs(int[][] graph, int removed, int[] initial) {
    Queue<Integer> q = new ArrayDeque<>();
    boolean[] seen = new boolean[graph.length];
    seen[removed] = true;

    int count = 0;

    for (final int i : initial)
      if (i != removed) {
        q.offer(i);
        seen[i] = true;
      }

    while (!q.isEmpty()) {
      final int u = q.poll();
      ++count;
      for (int i = 0; i < graph.length; ++i) {
        if (seen[i])
          continue;
        if (i != u && graph[i][u] == 1) {
          q.offer(i);
          seen[i] = true;
        }
      }
    }

    return count;
  }
}