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
- 51 lines of C++ from the credited upstream file 928.cpp.
- 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:3 int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {4 int ans = 0;5 int minCount = graph.size();6 7 ranges::sort(initial);8 9 for (const int i : initial) {10 const int count = bfs(graph, i, initial);11 if (count < minCount) {12 minCount = count;13 ans = i;14 }15 }16 17 return ans;18 }19 20 private:21 int bfs(const vector<vector<int>>& graph, int removed, vector<int>& initial) {22 queue<int> q;23 vector<bool> seen(graph.size());24 seen[removed] = true;25 26 int count = 0;27 28 for (const int i : initial)29 if (i != removed) {30 q.push(i);31 seen[i] = true;32 }33 34 while (!q.empty()) {35 const int u = q.front();36 q.pop();37 ++count;38 for (int i = 0; i < graph.size(); ++i) {39 if (seen[i])40 continue;41 if (i != u && graph[i][u]) {42 q.push(i);43 seen[i] = true;44 }45 }46 }47 48 return count;49 }50};51