LeetCode
LeetCode 924 Minimize Malware Spread - Hard
924. Minimize Malware Spread -- Hard
924. Minimize Malware Spread — Hard
Problem
- Minimize Malware Spread -- 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
Solution
class UnionFind:
def __init__(self, n):
self.parents = [i for i in range(n)]
self.rank = [1]*n
def find(self, x):
if x != self.parents[x]:
# path compression, recursively
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
# find root parents
px, py = self.find(x), self.find(y)
if px == py:
return
if self.rank[px] > self.rank[py]:
self.parents[py] = px
self.rank[px] += self.rank[py]
elif self.rank[px] < self.rank[py]:
self.parents[px] = py
self.rank[py] += self.rank[px]
else:
# 如果相等,加rank
self.parents[px] = py
self.rank[py] += self.rank[px]
return
class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
n = len(graph)
UF = UnionFind(n)
for i in range(n):
for j in range(n):
if graph[i][j] == 1:
UF.union(i, j)
infected = collections.defaultdict(int)
for node in initial:
infected[UF.find(node)] += 1
maxSize, candidate = 0, min(initial)
for node in initial:
parent = UF.find(node)
infections = infected[parent]
curSize = UF.rank[parent]
if infections > 1:
continue
if maxSize < curSize:
maxSize = curSize
candidate = node
elif maxSize == curSize and node < candidate:
candidate = node
return candidate