Approach
Breadth-first search
For Minimize Malware Spread II, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 48 lines of Java from the credited upstream file 928.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int minMalwareSpread(int[][] graph, int[] initial) {3 int ans = 0;4 int minCount = graph.length;5 6 Arrays.sort(initial);7 8 for (final int i : initial) {9 final int count = bfs(graph, i, initial);10 if (count < minCount) {11 minCount = count;12 ans = i;13 }14 }15 16 return ans;17 }18 19 private int bfs(int[][] graph, int removed, int[] initial) {20 Queue<Integer> q = new ArrayDeque<>();21 boolean[] seen = new boolean[graph.length];22 seen[removed] = true;23 24 int count = 0;25 26 for (final int i : initial)27 if (i != removed) {28 q.offer(i);29 seen[i] = true;30 }31 32 while (!q.isEmpty()) {33 final int u = q.poll();34 ++count;35 for (int i = 0; i < graph.length; ++i) {36 if (seen[i])37 continue;38 if (i != u && graph[i][u] == 1) {39 q.offer(i);40 seen[i] = true;41 }42 }43 }44 45 return count;46 }47}48