924. Minimize Malware Spread

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/83045493

In a network of nodes, each node i is directly connected to another node j if and only 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 one node from the initial list.  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 may still be infected later as a result of the malware spread.

Example 1:

Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0

Example 2:

Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0

Example 3:

Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1

Note:

扫描二维码关注公众号,回复: 4134064 查看本文章
  1. 1 < graph.length = graph[0].length <= 300
  2. 0 <= graph[i][j] == graph[j][i] <= 1
  3. graph[i][i] = 1
  4. 1 <= initial.length < graph.length
  5. 0 <= initial[i] < graph.length

思路:BFS求group,统计init中不同group的cnt,取cnt为1的,index最小的

class Solution(object):
    def minMalwareSpread(self, graph, initial):
        """
        :type graph: List[List[int]]
        :type initial: List[int]
        :rtype: int
        """
        n=len(graph)
        g=0
        a=[-1]*len(graph)
        cnt=[0]*(1+len(graph))
        vis=[False]*len(graph)
        for i in range(n):
            if vis[i]: continue
            g+=1
            q=[i]
            while q:
                s=q.pop()
                vis[s]=True
                a[s]=g
                cnt[g]+=1
                for t in range(n):
                    if graph[s][t]==1 and not vis[t]: q.append(t)
        initial.sort()
        affected=[0]*(1+n)
        for i in initial: affected[a[i]]+=1
        res,ma=initial[0],0
        for i in initial:
            if affected[a[i]]>1: continue 
            if cnt[a[i]]>ma:
                res,ma=i,cnt[a[i]]
            elif cnt[a[i]]==ma and res>i:
                res=i
        return res
    
    
s=Solution()
print(s.minMalwareSpread(graph = [[1,0,0,0],[0,1,0,0],[0,0,1,1],[0,0,1,1]], initial = [3,1]))
print(s.minMalwareSpread(graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]))
print(s.minMalwareSpread(graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]))
print(s.minMalwareSpread(graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]))


猜你喜欢

转载自blog.csdn.net/zjucor/article/details/83045493