Approach
Depth-first search
For Contain Virus, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 86 lines of C++ from the credited upstream file 749.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 6 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Region {2 3 4 unordered_set<int> infected;5 unordered_set<int> noninfected;6 int wallsRequired = 0;7};8 9class Solution {10 public:11 int containVirus(vector<vector<int>>& isInfected) {12 const int m = isInfected.size();13 const int n = isInfected[0].size();14 int ans = 0;15 16 while (true) {17 vector<Region> regions;18 vector<vector<bool>> seen(m, vector<bool>(n));19 20 for (int i = 0; i < m; ++i)21 for (int j = 0; j < n; ++j)22 if (isInfected[i][j] == 1 && !seen[i][j]) {23 Region region;24 25 dfs(isInfected, i, j, region, seen);26 if (!region.noninfected.empty())27 regions.push_back(region);28 }29 30 if (regions.empty())31 break; 32 33 34 35 ranges::sort(regions, ranges::less{}, [](const Region& region) {36 return region.noninfected.size();37 });38 39 40 Region mostInfectedRegion = regions.back();41 regions.pop_back();42 ans += mostInfectedRegion.wallsRequired;43 44 for (const int neighbor : mostInfectedRegion.infected) {45 const int i = neighbor / n;46 const int j = neighbor % n;47 48 isInfected[i][j] = 2;49 }50 51 52 for (const Region& region : regions)53 for (const int neighbor : region.noninfected) {54 const int i = neighbor / n;55 const int j = neighbor % n;56 isInfected[i][j] = 1;57 }58 }59 60 return ans;61 }62 63 private:64 void dfs(const vector<vector<int>>& isInfected, int i, int j, Region& region,65 vector<vector<bool>>& seen) {66 if (i < 0 || i == isInfected.size() || j < 0 || j == isInfected[0].size())67 return;68 if (seen[i][j] || isInfected[i][j] == 2)69 return;70 if (isInfected[i][j] == 0) {71 region.noninfected.insert(i * isInfected[0].size() + j);72 ++region.wallsRequired;73 return;74 }75 76 77 seen[i][j] = true;78 region.infected.insert(i * isInfected[0].size() + j);79 80 dfs(isInfected, i + 1, j, region, seen);81 dfs(isInfected, i - 1, j, region, seen);82 dfs(isInfected, i, j + 1, region, seen);83 dfs(isInfected, i, j - 1, region, seen);84 }85};86