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.
This approach uses BFS to explore each contaminated region and calculate the number of walls needed to quarantine it. We visit each cell in the grid and use BFS to collect all connected infected cells into a region while counting uninfected neighbors and the walls needed. We then prioritize based on the number of cells threatened.
The BFS approach starts by iterating over each cell in the grid. For each new contaminated cell (not previously visited), it initiates a BFS to explore the entire contiguous region of infected cells. During this BFS, we collect cells that are part of the region, count neighboring uninfected cells, and calculate how many walls are required. The regions are prioritized by the number of uninfected cells they threaten. On each 'day', we choose the most dangerous region to quarantine, mark it, and allow other regions to spread.
Time complexity is O(m * n) in worst-case since we potentially visit each cell once. Each BFS operation processes all cells in the connected components and calculates using neighbor checks. Space complexity is also O(m * n) due to additional data structures used for bfs state.
This approach leverages DFS to explore and manage the infected regions. Similar to BFS, DFS identifies contiguous regions, evaluates threats to nearby uninfected cells, and calculates the required protective walls. DFS is suitable due to its natural recursion stack management for exploring all paths fully per region.
This C++ implementation uses DFS to explore each region of infected cells. Each call to DFS processes all cells reachable from the starting cell, calculates the surrounding walls required for containment, and collects nearby uninfected neighbors as potential new infection threats. DFS naturally traverses deeper paths first before backing up, making it well-suited for full region exploration here.
C++
JavaScript
The time complexity of the DFS implementation is O(m * n), due to examining each cell individually and performing DFS requiring additional path exploration. Space complexity is similar, O(m * n), from recursion stack depth and temporary data for regions and threats compound.
| Approach | Complexity |
|---|---|
| Breadth-First Search (BFS) for Contaminated Regions | Time complexity is O(m * n) in worst-case since we potentially visit each cell once. Each BFS operation processes all cells in the connected components and calculates using neighbor checks. Space complexity is also O(m * n) due to additional data structures used for bfs state. |
| Depth-First Search (DFS) for Contaminated Regions | The time complexity of the DFS implementation is O(m * n), due to examining each cell individually and performing DFS requiring additional path exploration. Space complexity is similar, O(m * n), from recursion stack depth and temporary data for regions and threats compound. |
| Default Approach | — |
| 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 |
花花酱 LeetCode 749. Contain Virus - 刷题找工作 EP136 • Hua Hua • 3,723 views views
Watch 7 more video solutions →Practice Contain Virus with our built-in code editor and test cases.
Practice on FleetCode