LeetCode Solutions

928. Minimize Malware Spread II

Time: $O(n^2k)$, where $n = |\texttt{graph}|$ and $k = |\texttt{initial}|$

Space: $O(n)$

			

class Solution {
 public:
  int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
    int ans = 0;
    int minCount = graph.size();

    sort(begin(initial), end(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;
  }
};
			

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;
  }
}