1
var minMalwareSpread = function (graph, initial) {4
for (let i = 0; i < n; i++) {5
for (let j = i + 1; j < n; j++) {6
if (graph[i][j]) uf.union(i, j);10
// Get number of nodes in each connected component12
for (let i = 0; i < n; i++) {13
let parent = uf.find(i);14
nodesCount[parent] = (nodesCount[parent] || 0) + 1;17
// Find the initial node connected to the most amount of other nodes, where it is the only malware infected node in its group.20
for (let node of initial) {21
let malwareNodes = malwareConnected(node);22
let parent = uf.find(node);23
let nodesAffected = malwareNodes === 1 ? nodesCount[parent] : 0;24
if (nodesAffected > max || (nodesAffected === max && node < res)) {31
function malwareConnected(node) {32
// gets number of malware infected nodes connected to node34
for (let malware of initial) {35
if (uf.isConnected(node, malware)) count++;43
this.rank = Array(size);44
this.root = Array(size);45
for (let i = 0; i < size; i++) {51
if (this.root[x] === x) return x;52
return (this.root[x] = this.find(this.root[x]));55
let rootX = this.find(x),57
if (rootX === rootY) return false;58
if (this.rank[rootX] < this.rank[rootY]) this.root[rootX] = rootY;59
else if (this.rank[rootX] > this.rank[rootY]) this.root[rootY] = rootX;61
this.root[rootY] = rootX;67
return this.find(x) === this.find(y);