924.尽量减少恶意软件的传播

尽量减少恶意软件的传播

给出了一个由 n 个节点组成的网络,用 n × n 个邻接矩阵图 graph 表示。在节点网络中,当 graph[i][j] = 1 时,表示节点 i 能够直接连接到另一个节点 j。

一些节点 initial 最初被恶意软件感染。只要两个节点直接连接,且其中至少一个节点受到恶意软件的感染,那么两个节点都将被恶意软件感染。这种恶意软件的传播将继续,直到没有更多的节点可以被这种方式感染。

假设 M(initial) 是在恶意软件停止传播之后,整个网络中被感染节点的最终数量。

我们可以从 initial 中删除一个节点,并完全移除该节点以及从该节点到任何其他节点的任何连接。请返回移除后能够使 M(initial) 最小化的节点。如果有多个节点满足条件,返回索引最小的那个节点。

示例 1:

输入:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
输出:0

示例 2:

输入:graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,1]
输出:0

提示:

  • n == graph.length
  • n == graph[i].length
  • 2 <= n <= 300
  • graph[i][j] == 0 或 1
  • graph[i][j] == graph[j][i]
  • graph[i][i] == 1
  • 1 <= initial.length <= n
  • 0 <= initial[i] <= n - 1
  • initial 中所有整数均不重复

解析

使用并查集找出每个连通分量,统计每个连通分量的大小。对于 initial 中的每个节点,如果它是唯一被感染的节点,则移除它可以拯救整个连通分量。选择能拯救最多节点的节点。

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
var minMalwareSpread = function (graph, initial) {
const n = graph.length;
const parent = Array.from({ length: n }, (_, i) => i);
const size = new Array(n).fill(1);

function find(x) {
if (parent[x] !== x) {
parent[x] = find(parent[x]);
}
return parent[x];
}

function union(x, y) {
const px = find(x);
const py = find(y);
if (px !== py) {
parent[px] = py;
size[py] += size[px];
}
}

for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (graph[i][j] === 1) {
union(i, j);
}
}
}

const initialSet = new Set(initial);
const infectedCount = new Map();

for (const node of initial) {
const root = find(node);
infectedCount.set(root, (infectedCount.get(root) || 0) + 1);
}

let result = Math.min(...initial);
let maxSize = -1;

for (const node of initial) {
const root = find(node);
if (infectedCount.get(root) === 1) {
if (size[root] > maxSize) {
maxSize = size[root];
result = node;
} else if (size[root] === maxSize && node < result) {
result = node;
}
}
}

return result;
};

时间复杂度 O(n²),空间复杂度 O(n)。


924.尽量减少恶意软件的传播
https://leetcode.lz5z.com/924.minimize-malware-spread/
作者
tickli
发布于
2025年1月9日
许可协议