Watch 8 video solutions for Contain Virus, a hard level problem involving Array, Depth-First Search, Breadth-First Search. This walkthrough by Hua Hua has 3,723 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.
Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.
Example 1:
Input: isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]] Output: 10 Explanation: There are 2 contaminated regions. On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
![]()
Example 2:
Input: isInfected = [[1,1,1],[1,0,1],[1,1,1]] Output: 4 Explanation: Even though there is only one cell saved, there are 4 walls built. Notice that walls are only built on the shared boundary of two different cells.
Example 3:
Input: isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]] Output: 13 Explanation: The region on the left only builds two new walls.
Constraints:
m == isInfected.lengthn == isInfected[i].length1 <= m, n <= 50isInfected[i][j] is either 0 or 1.Problem Overview: You are given a grid where 1 represents infected cells and 0 represents uninfected cells. Each day, the virus spreads to neighboring cells unless you quarantine one infected region by building walls around it. The goal is to repeatedly identify the region that threatens the most new cells, build walls around it, and allow the remaining regions to spread. Return the total number of walls built during the process.
The challenge is identifying infected regions, measuring their potential spread (frontier cells), and simulating the daily containment process. Each iteration requires exploring connected components, tracking boundaries, and updating the grid state. Graph traversal techniques like Breadth-First Search and Depth-First Search work naturally because the grid behaves like a graph where each cell connects to its four neighbors.
Approach 1: Breadth-First Search (BFS) for Contaminated Regions (Time: O((m*n)^2), Space: O(m*n))
Scan the grid each day and start a BFS whenever you encounter an unvisited infected cell. The BFS collects all cells in the same infected region, tracks the neighboring healthy cells that could be infected next (the frontier), and counts the number of walls required to isolate the region. Store this information for every region discovered during the scan. After processing all regions, select the region with the largest frontier and quarantine it by converting its cells to a blocked state.
The remaining regions spread normally. Iterate through their frontier cells and convert those healthy cells to infected ones. Repeat the process until no region can spread further. BFS is intuitive for layer-by-layer exploration and works well when you want to track neighboring cells and boundaries in a matrix grid.
Approach 2: Depth-First Search (DFS) for Contaminated Regions (Time: O((m*n)^2), Space: O(m*n))
The DFS version follows the same containment strategy but explores regions using recursion or an explicit stack. When you encounter an infected cell, run DFS to collect all connected infected cells, record the unique healthy neighbors they threaten, and count the required walls along the boundary. Each DFS call marks visited cells so the same region is not processed twice.
After identifying all regions, select the one threatening the most cells and quarantine it. Mark its cells as contained, while the other regions expand into their frontier cells. Continue repeating the detection and spread cycle until no infected region can grow further. DFS often produces simpler implementations when recursively exploring connected components in grid-based simulation problems.
Recommended for interviews: Both BFS and DFS solutions are acceptable because the core challenge is the simulation logic, not the traversal method. Interviewers typically expect you to model regions, track frontier cells with sets, and repeatedly quarantine the most dangerous region. A correct implementation with O((m*n)^2) time complexity demonstrates strong grid traversal and simulation skills.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| BFS for Contaminated Regions | O((m*n)^2) | O(m*n) | When you prefer queue-based level traversal and explicit frontier tracking |
| DFS for Contaminated Regions | O((m*n)^2) | O(m*n) | When implementing recursive connected-component exploration in grid problems |