Created
January 21, 2020 13:09
-
-
Save fengyitsai/e873f694cdd29e63f13e719398dbc4f0 to your computer and use it in GitHub Desktop.
928. Minimize Malware Spread II
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func minMalwareSpread(_ graph: [[Int]], _ initial: [Int]) -> Int { | |
var record = [Int:[Int]]() | |
let initialSet = Set(initial) | |
for start in initial { | |
var visited = initialSet | |
var queue = [start] | |
while !queue.isEmpty { | |
var nextQueue = [Int]() | |
for node in queue { | |
let array = graph[node] | |
for i in 0..<array.count where array[i] == 1 && !visited.contains(i) { | |
nextQueue.append(i) | |
visited.insert(i) | |
record[i, default:[Int]()].append(start) | |
} | |
} | |
queue = nextQueue | |
} | |
} | |
var result = [Int](repeating:0 ,count: graph.count) | |
for (key, value) in record where value.count == 1 { | |
for node in value { | |
result[node] += 1 | |
} | |
} | |
let maxValue = result.max() ?? 0 | |
for i in initial.sorted() where result[i] == maxValue { | |
return i | |
} | |
return initial[0] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment