-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.py
39 lines (36 loc) · 1.13 KB
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
def union(a, b):
pa, pb = find(a), find(b)
if pa != pb:
size[pb] += size[pa]
p[pa] = pb
n = len(graph)
p = list(range(n))
size = [1] * n
clean = [True] * n
for i in initial:
clean[i] = False
for i in range(n):
if not clean[i]:
continue
for j in range(i + 1, n):
if clean[j] and graph[i][j] == 1:
union(i, j)
cnt = Counter()
mp = {}
for i in initial:
s = {find(j) for j in range(n) if clean[j] and graph[i][j] == 1}
for root in s:
cnt[root] += 1
mp[i] = s
mx, ans = -1, 0
for i, s in mp.items():
t = sum(size[root] for root in s if cnt[root] == 1)
if mx < t or mx == t and i < ans:
mx, ans = t, i
return ans