924. Minimize Malware Spread

Question

In a network of nodes, each node i is directly connected to another node j if and only 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 one node from the initial list. 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.

Note that if a node was removed from the initial list of infected nodes, it may still be infected later as a result of the malware spread.

Example 1:

Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0
Example 2:

Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0
Example 3:

Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1

Note:

  1. 1 < graph.length = graph[0].length <= 300
  2. 0 <= graph[i][j] == graph[j][i] <= 1
  3. graph[i][i] = 1
  4. 1 <= initial.length < graph.length
  5. 0 <= initial[i] < graph.length

Solution

  • Method 1: Union find AC 94.98%
    class Solution {
        private int len;
        private int[] uf;
        private int[] count;    
        public int minMalwareSpread(int[][] graph, int[] initial) {
            len = graph.length;
            uf = new int[len];
            count = new int[len];
            for(int i = 0; i < len; i++){
                uf[i] = i;
                count[i] = 1;
            }
            for(int i = 0; i < len; i++){
                for(int j = i; j < len; j++){
                    if(i == j || graph[i][j] == 0) continue;
                    union(i, j);
                }
            }
            Set<Integer> set = new HashSet<>();
            for(int ini : initial){
                int root = find(ini);
                if(set.contains(root)){
                    count[root] = 0;
                    continue;
                }
                set.add(root);
            }
            Arrays.sort(initial);
            int max = -1;
            int res = -1;
            for(int ini : initial){
                int p = find(ini);
                if(count[p] > max){
                    max = count[p];
                    res = ini;
                }
            }
            return res;
        }
        private int find(int i){
            if(uf[i] != i){
                uf[i] = find(uf[i]);
            }
            return uf[i];
        }
        private void union(int i, int j){
            int p = find(i);
            int q = find(j);
            uf[p] = q;
            count[q] += count[p];
        }
    }