Problem solution · Java

Contain Virus

Contain Virus: a Java solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
81 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeContain Virus · JavaJava
Use this to learn the idea, then write your own version.
class Region {  // Given m = the number of rows and n = the number of columns, (x, y) will be  // hashed as x * n + y.  public Set<Integer> infected = new HashSet<>();  public Set<Integer> noninfected = new HashSet<>();  public int wallsRequired = 0;} class Solution {  public int containVirus(int[][] isInfected) {    final int m = isInfected.length;    final int n = isInfected[0].length;    int ans = 0;     while (true) {      List<Region> regions = new ArrayList<>();      boolean[][] seen = new boolean[m][n];       for (int i = 0; i < m; ++i)        for (int j = 0; j < n; ++j)          if (isInfected[i][j] == 1 && !seen[i][j]) {            Region region = new Region();            // Use DFS to find all the regions (1s).            dfs(isInfected, i, j, region, seen);            if (!region.noninfected.isEmpty())              regions.add(region);          }       if (regions.isEmpty())        break; // No region causes further infection.       // Regions that infect the most neighbors will be sorted to the back of      // the array.      Collections.sort(regions, (a, b) -> a.noninfected.size() - b.noninfected.size());       // Build walls around the region that infects the most neighbors.      Region mostInfectedRegion = regions.get(regions.size() - 1);      regions.remove(regions.size() - 1);      ans += mostInfectedRegion.wallsRequired;       for (final int neighbor : mostInfectedRegion.infected) {        final int i = neighbor / n;        final int j = neighbor % n;        // The isInfected is now contained and won't be infected anymore.        isInfected[i][j] = 2;      }       // For remaining regions, infect their neighbors.      for (final Region region : regions)        for (final int neighbor : region.noninfected) {          final int i = neighbor / n;          final int j = neighbor % n;          isInfected[i][j] = 1;        }    }     return ans;  }   private void dfs(int[][] isInfected, int i, int j, Region region, boolean[][] seen) {    if (i < 0 || i == isInfected.length || j < 0 || j == isInfected[0].length)      return;    if (seen[i][j] || isInfected[i][j] == 2)      return;    if (isInfected[i][j] == 0) {      region.noninfected.add(i * isInfected[0].length + j);      ++region.wallsRequired;      return;    }     // isInfected[i][j] == 1    seen[i][j] = true;    region.infected.add(i * isInfected[0].length + j);     dfs(isInfected, i + 1, j, region, seen);    dfs(isInfected, i - 1, j, region, seen);    dfs(isInfected, i, j + 1, region, seen);    dfs(isInfected, i, j - 1, region, seen);  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗