难度: Hard
原题连接
内容描述
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:
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
思路 1 - 时间复杂度: O(len(graph)^2)- 空间复杂度: O(len(graph))******
比赛中sb了,一直用dfs超时,最后想到直接用并查集就行了,拍断大腿,本来稳稳前50的(自己欺骗自己😂😂😂)
思路就是看看initial里面哪个index最小的点所在的联通分量size最大
其中要注意每个initial中元素ini所在的联通分量我们还要去除它里面含有的本身就在initial中的其他元素,因为对于这些元素,事实上即使我们删除了ini,也minimize不了它们。所以要算一下每个initial里面的元素所在的联通分量里面包含的其他的initial元素的个数,代码中用dup表示
graph长度为N,
find()时间复杂度为O(N), union为O(1),所以最终时间复杂度为O(len(graph)^2)
空间为O(N)
class Solution(object):
def minMalwareSpread(self, graph, initial):
"""
:type graph: List[List[int]]
:type initial: List[int]
:rtype: int
"""
def find(x):
while x != uf[x]:
uf[x] = uf[uf[x]]
x = uf[x]
return uf[x]
def union(x, y):
x_root = find(x)
y_root = find(y)
uf[x_root] = y_root
uf = [i for i in range(len(graph))]
for i in range(len(graph)):
for j in range(i+1, len(graph)):
if graph[i][j]:
union(i, j)
lookup, dup = {}, {}
for i in range(len(graph)):
root = find(i)
lookup[root] = lookup.get(root, 0) + 1
if i in initial: # 这里是算一下每个initial里面的元素所在的联通分量里面包含的其他的initial元素的个数
dup[root] = dup.get(root, -1) + 1 # 这里默认值是-1就代表不把自己包含进去了,算的是所有其他initial元素的个数
component_sizes_of_initial = [lookup[find(ini)]-dup[find(ini)] for ini in initial]
max_component_size = max(component_sizes_of_initial)
res = []
for i in range(len(initial)):
if component_sizes_of_initial[i] == max_component_size:
res.append(initial[i])
return min(res)