-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimizeMalwareSpreadII.py
More file actions
34 lines (29 loc) · 1.08 KB
/
minimizeMalwareSpreadII.py
File metadata and controls
34 lines (29 loc) · 1.08 KB
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
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/minimize-malware-spread-ii/
# Author: Miao Zhang
# Date: 2021-03-26
class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
n = len(graph)
clean = set(range(n)) - set(initial)
def dfs(u, seen):
for i in range(len(graph[u])):
if graph[u][i] and i in clean and i not in seen:
seen.add(i)
dfs(i, seen)
infected_by = {v: [] for v in clean}
for u in initial:
seen = set()
dfs(u, seen)
for v in seen:
infected_by[v].append(u)
contribution = collections.Counter()
for k, v in infected_by.items():
if len(v) == 1:
contribution[v[0]] += 1
best = (-1, min(initial))
for u, score in contribution.items():
if score > best[0] or score == best[0] and u < best[1]:
best = score, u
return best[1]