leetcode-pp / 91alg-13-daily-check

0 stars 0 forks source link

【Day 77 】2024-06-23 - 924. 尽量减少恶意软件的传播 #78

Open azl397985856 opened 1 week ago

azl397985856 commented 1 week ago

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

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/minimize-malware-spread

前置知识

暂无

题目描述

在节点网络中,只有当 graph[i][j] = 1 时,每个节点 i 能够直接连接到另一个节点 j。

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

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

我们可以从初始列表中删除一个节点。如果移除这一节点将最小化 M(initial), 则返回该节点。如果有多个节点满足条件,就返回索引最小的节点。

请注意,如果某个节点已从受感染节点的列表 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,2]
输出:0
示例 3:

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

提示:

1 < graph.length = graph[0].length <= 300
0 <= graph[i][j] == graph[j][i] <= 1
graph[i][i] == 1
1 <= initial.length < graph.length
0 <= initial[i] < graph.length
Dtjk commented 1 week ago

class Solution { public int minMalwareSpread(int[][] graph, int[] initial) { Arrays.sort(initial); int N = graph.length; int ans = initial[0]; int max = 0; boolean[] init = new boolean[N]; for (int p : initial) { init[p] = true; } for (int p : initial) { init[p] = false; int count = process(graph, p, new boolean[N], init); if (count > max) { max = count; ans = p; } init[p] = true; } return ans; }

private int process(int[][] graph, int p, boolean[] visited, boolean[] initial) {
    if (initial[p]) {
        return 0;
    }
    visited[p] = true;
    int count = 1;
    for (int q = 0; q < graph[p].length; q++) {
        if (!visited[q] && graph[p][q] == 1) {
            int c = process(graph, q, visited, initial);
            if (c == 0) {
                return 0;
            }
            count += c;
        }
    }
    return count;
}

}