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
- 81 lines of Java from the credited upstream file 749.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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.
1class Region {2 3 4 public Set<Integer> infected = new HashSet<>();5 public Set<Integer> noninfected = new HashSet<>();6 public int wallsRequired = 0;7}8 9class Solution {10 public int containVirus(int[][] isInfected) {11 final int m = isInfected.length;12 final int n = isInfected[0].length;13 int ans = 0;14 15 while (true) {16 List<Region> regions = new ArrayList<>();17 boolean[][] seen = new boolean[m][n];18 19 for (int i = 0; i < m; ++i)20 for (int j = 0; j < n; ++j)21 if (isInfected[i][j] == 1 && !seen[i][j]) {22 Region region = new Region();23 24 dfs(isInfected, i, j, region, seen);25 if (!region.noninfected.isEmpty())26 regions.add(region);27 }28 29 if (regions.isEmpty())30 break; 31 32 33 34 Collections.sort(regions, (a, b) -> a.noninfected.size() - b.noninfected.size());35 36 37 Region mostInfectedRegion = regions.get(regions.size() - 1);38 regions.remove(regions.size() - 1);39 ans += mostInfectedRegion.wallsRequired;40 41 for (final int neighbor : mostInfectedRegion.infected) {42 final int i = neighbor / n;43 final int j = neighbor % n;44 45 isInfected[i][j] = 2;46 }47 48 49 for (final Region region : regions)50 for (final int neighbor : region.noninfected) {51 final int i = neighbor / n;52 final int j = neighbor % n;53 isInfected[i][j] = 1;54 }55 }56 57 return ans;58 }59 60 private void dfs(int[][] isInfected, int i, int j, Region region, boolean[][] seen) {61 if (i < 0 || i == isInfected.length || j < 0 || j == isInfected[0].length)62 return;63 if (seen[i][j] || isInfected[i][j] == 2)64 return;65 if (isInfected[i][j] == 0) {66 region.noninfected.add(i * isInfected[0].length + j);67 ++region.wallsRequired;68 return;69 }70 71 72 seen[i][j] = true;73 region.infected.add(i * isInfected[0].length + j);74 75 dfs(isInfected, i + 1, j, region, seen);76 dfs(isInfected, i - 1, j, region, seen);77 dfs(isInfected, i, j + 1, region, seen);78 dfs(isInfected, i, j - 1, region, seen);79 }80}81