-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMinimizeMalwareSpread2.java
41 lines (40 loc) · 1.41 KB
/
MinimizeMalwareSpread2.java
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
40
41
/*https://leetcode.com/problems/minimize-malware-spread-ii/*/
class Solution {
public int minMalwareSpread(int[][] graph, int[] initial) {
int nodes, min = Integer.MAX_VALUE, count = 0, target, N = graph.length, result = -1;
for (int i = 0; i < initial.length; ++i)
{
target = initial[i];
Queue<Integer> queue = new LinkedList<Integer>();
for (int node : initial)
if (node != target)
queue.add(node);
HashSet<Integer> infected = new HashSet<Integer>();
for (int node : initial)
infected.add(node);
infected.remove(target);
while (!queue.isEmpty())
{
int curr = queue.poll();
if (curr == target) continue;
for (int adj = 0; adj < N; ++adj)
{
if (adj == target) continue;
if (graph[curr][adj] == 1 && !infected.contains(adj))
{
infected.add(adj);
queue.add(adj);
}
}
}
if (infected.size() < min)
{
min = infected.size();
result = target;
}
else if (infected.size() == min && target < result)
result = target;
}
return result;
}
}