题目如下:
In a network of nodes, each node
i
is directly connected to another nodej
if and only ifgraph[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 minimizeM(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:
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
解题思路:本题可以采用并查集。首先利用并查集把graph中各个节点进行分组,同一个组的元素只要有一个被infected,那么其他的都会被infected,接下来遍历initial中的元素,如果initial中的元素有两个或者两个以上属于同一个组的话,那么从initial中去除这几个元素中的任何一个都无法减少infected nodes的数量。所以题目就演变成了从initial中找出和其他元素均不属于同一个组,并且这个元素的所属的组包含最多的元素。最后要提醒下,题目要求返回如果有多个答案的话返回索引最小的那个,这里指的不是initial中的索引,而是graph中的索引,就是指数值最小的值。
吐槽:Leetcode UI改版后,感觉看题目和提交代码没这么方便了。
代码如下:
class Solution(object): def minMalwareSpread(self, graph, initial): """ :type graph: List[List[int]] :type initial: List[int] :rtype: int """ parent = [i for i in range(len(graph))] def find(v,p): if p[v] == v: return v return find(p[v],p) def union(v1,v2): p1 = find(v1,parent) p2 = find(v2,parent) if p1 < p2: parent[p2] = p1 else: parent[p1] = p2 for i in range(len(graph)): for j in range(len(graph[i])): if i != j and graph[i][j] == 1: union(i,j) dic = {} for i in range(len(graph)): p = find(i, parent) dic[p] = dic.setdefault(p,0) + 1 pl = [] for i in initial: p = find(i,parent) pl.append(p) res = None count = 0 for i in initial: p = find(i, parent) if pl.count(p) == 1: if count < dic[p]: count = dic[p] res = i elif count == dic[p]: res = min(res,i) if res == None: res = min(initial) return res