LeetCode 924 Minimize Malware Spread (Python)

Posted by 小明MaxMing on October 13, 2024

题目

You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.

Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.

Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial.

Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.

Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.

解题思路

从每个初始被感染的点开始进行dfs,如果不会遇到其他初始点,则更新结果为dfs的总点数,否则移除这个点不会影响结果

代码

class Solution:
    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:        
        n = len(graph)
        M = [-1] * n
        sini = set(initial)
        for ini in initial:
            if M[ini] != -1:
                continue
            s = [ini]
            visited = {ini}
            is_mul = False
            while s:
                cur = s.pop()
                for k in range(n):
                    if k not in visited and graph[cur][k]:
                        s.append(k)
                        visited.add(k)
                        if k in sini:
                            is_mul = True
            for node in visited:
                M[node] = 0 if is_mul else len(visited)
        res = maxm = -1
        for ini in initial:
            if M[ini] > maxm:
                maxm = M[ini]
                res = ini
            if M[ini] == maxm:
                res = min(res, ini)
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅