0%

Leetcode924-Minimize Malware Spread

Description

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

Example 1:

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

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

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

Note:

  • 1 < graph.length = graph[0].length <= 300
  • 0 <= graph[i][j] == graph[j][i] <= 1
  • graph[i][i] == 1
  • 1 <= initial.length <= graph.length
  • 0 <= initial[i] < graph.length

Solution

Union found all nodes.

Count the union size of each union set.

Count the malware number of each union set.

Return the biggest union’s malware if there is one and only one malware.

If no such union that has and has only one malware,

return the malware with minimum index.

  • Time Complexity:
  • Space Complexity:
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
class Solution {
private int[] parent;
public int minMalwareSpread(int[][] graph, int[] initial) {
int n = graph.length;
parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (graph[i][j] == 1) union(i, j);
}
}

int[] unionSize = new int[n];
int[] malwareSize = new int[n];
for (int i = 0; i < n; i++){
unionSize[find(i)]++;
}
for (int i: initial){
malwareSize[find(i)]++;
}

int max = 0;
int res = -1;
Arrays.sort(initial);
for (int i: initial){
int idx = find(i);
if (malwareSize[idx] == 1 && unionSize[idx] > max){
max = unionSize[idx];
res = i;
}
}
return res == -1 ? initial[0] : res;
}

private void union(int i, int j){
parent[find(i)] = find(j);
}

private int find(int i){
if (parent[i] != i)
parent[i] = find(parent[i]);
return parent[i];
}
}