|
| 1 | +/** |
| 2 | + * 924. Minimize Malware Spread |
| 3 | + * https://leetcode.com/problems/minimize-malware-spread/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith |
| 7 | + * node is directly connected to the jth node if graph[i][j] == 1. |
| 8 | + * |
| 9 | + * Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, |
| 10 | + * and at least one of those two nodes is infected by malware, both nodes will be infected b |
| 11 | + * malware. This spread of malware will continue until no more nodes can be infected in this manner. |
| 12 | + * |
| 13 | + * Suppose M(initial) is the final number of nodes infected with malware in the entire network after |
| 14 | + * the spread of malware stops. We will remove exactly one node from initial. |
| 15 | + * |
| 16 | + * Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed |
| 17 | + * to minimize M(initial), return such a node with the smallest index. |
| 18 | + * |
| 19 | + * Note that if a node was removed from the initial list of infected nodes, it might still be |
| 20 | + * infected later due to the malware spread. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number[][]} graph |
| 25 | + * @param {number[]} initial |
| 26 | + * @return {number} |
| 27 | + */ |
| 28 | +var minMalwareSpread = function(graph, initial) { |
| 29 | + const n = graph.length; |
| 30 | + const parent = new Array(n).fill().map((_, i) => i); |
| 31 | + const size = new Array(n).fill(1); |
| 32 | + |
| 33 | + for (let i = 0; i < n; i++) { |
| 34 | + for (let j = i + 1; j < n; j++) { |
| 35 | + if (graph[i][j] === 1) { |
| 36 | + union(i, j); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + let maxSize = 0; |
| 42 | + let result = Math.min(...initial); |
| 43 | + |
| 44 | + for (const node of initial) { |
| 45 | + const root = find(node); |
| 46 | + let componentInfected = 0; |
| 47 | + |
| 48 | + for (const infectedNode of initial) { |
| 49 | + if (find(infectedNode) === root) { |
| 50 | + componentInfected++; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if (componentInfected === 1 && size[root] > maxSize) { |
| 55 | + maxSize = size[root]; |
| 56 | + result = node; |
| 57 | + } else if (componentInfected === 1 && size[root] === maxSize) { |
| 58 | + result = Math.min(result, node); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return result; |
| 63 | + |
| 64 | + function find(x) { |
| 65 | + if (parent[x] !== x) { |
| 66 | + parent[x] = find(parent[x]); |
| 67 | + } |
| 68 | + return parent[x]; |
| 69 | + } |
| 70 | + |
| 71 | + function union(x, y) { |
| 72 | + const rootX = find(x); |
| 73 | + const rootY = find(y); |
| 74 | + if (rootX !== rootY) { |
| 75 | + parent[rootX] = rootY; |
| 76 | + size[rootY] += size[rootX]; |
| 77 | + } |
| 78 | + } |
| 79 | +}; |
0 commit comments