-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0924-minimize-malware-spread.js
More file actions
69 lines (61 loc) · 2.19 KB
/
0924-minimize-malware-spread.js
File metadata and controls
69 lines (61 loc) · 2.19 KB
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
/**
* Minimize Malware Spread
* Time Complexity: O(N^2 * α(N))
* Space Complexity: O(N)
*/
var minMalwareSpread = function (graphMatrix, initiallyInfected) {
const totalNetworkNodes = graphMatrix.length;
const dsuParents = Array.from(
{ length: totalNetworkNodes },
(_, elementIndex) => elementIndex,
);
const componentMemberCounts = new Array(totalNetworkNodes).fill(1);
function findRepresentative(nodeIdentifier) {
if (dsuParents[nodeIdentifier] !== nodeIdentifier) {
dsuParents[nodeIdentifier] = findRepresentative(
dsuParents[nodeIdentifier],
);
}
return dsuParents[nodeIdentifier];
}
function uniteSets(firstNode, secondNode) {
const rootOfFirst = findRepresentative(firstNode);
const rootOfSecond = findRepresentative(secondNode);
if (rootOfFirst !== rootOfSecond) {
dsuParents[rootOfFirst] = rootOfSecond;
componentMemberCounts[rootOfSecond] += componentMemberCounts[rootOfFirst];
}
}
for (let nodeOneIndex = 0; nodeOneIndex < totalNetworkNodes; nodeOneIndex++) {
for (
let nodeTwoIndex = nodeOneIndex + 1;
nodeTwoIndex < totalNetworkNodes;
nodeTwoIndex++
) {
if (graphMatrix[nodeOneIndex][nodeTwoIndex] === 1) {
uniteSets(nodeOneIndex, nodeTwoIndex);
}
}
}
let maximumSavedComponentSize = 0;
let optimalNodeToRemove = Math.min(...initiallyInfected);
for (const candidateNode of initiallyInfected) {
const candidateRoot = findRepresentative(candidateNode);
let infectedCountInThisComponent = 0;
for (const checkNode of initiallyInfected) {
if (findRepresentative(checkNode) === candidateRoot) {
infectedCountInThisComponent++;
}
}
if (infectedCountInThisComponent === 1) {
const currentComponentActualSize = componentMemberCounts[candidateRoot];
if (currentComponentActualSize > maximumSavedComponentSize) {
maximumSavedComponentSize = currentComponentActualSize;
optimalNodeToRemove = candidateNode;
} else if (currentComponentActualSize === maximumSavedComponentSize) {
optimalNodeToRemove = Math.min(optimalNodeToRemove, candidateNode);
}
}
}
return optimalNodeToRemove;
};