-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path0924-minimize-malware-spread.js
79 lines (70 loc) · 2.24 KB
/
0924-minimize-malware-spread.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* 924. Minimize Malware Spread
* https://leetcode.com/problems/minimize-malware-spread/
* Difficulty: Hard
*
* 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 b
* 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.
*
* 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 might still be
* infected later due to the malware spread.
*/
/**
* @param {number[][]} graph
* @param {number[]} initial
* @return {number}
*/
var minMalwareSpread = function(graph, initial) {
const n = graph.length;
const parent = new Array(n).fill().map((_, i) => i);
const size = new Array(n).fill(1);
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (graph[i][j] === 1) {
union(i, j);
}
}
}
let maxSize = 0;
let result = Math.min(...initial);
for (const node of initial) {
const root = find(node);
let componentInfected = 0;
for (const infectedNode of initial) {
if (find(infectedNode) === root) {
componentInfected++;
}
}
if (componentInfected === 1 && size[root] > maxSize) {
maxSize = size[root];
result = node;
} else if (componentInfected === 1 && size[root] === maxSize) {
result = Math.min(result, node);
}
}
return result;
function find(x) {
if (parent[x] !== x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
function union(x, y) {
const rootX = find(x);
const rootY = find(y);
if (rootX !== rootY) {
parent[rootX] = rootY;
size[rootY] += size[rootX];
}
}
};