Skip to content

Practice Contain Virus

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Problem Statement

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. Practice approach: At the start of each day, flood-fill every active infected region. Record its set of distinct adjacent uninfected cells separately from its number of infected-to-uninfected boundary edges. Select the region with the largest threatened-cell set, add its boundary-edge count to the wall total, and mark it quarantined. Spread every other active region into its previously recorded frontier simultaneously, then recompute regions for the next day. Stop when no region threatens an uninfected cell. The distinction between cells and edges matters: in a 3 by 3 grid with an infected outer ring and an uninfected center, only one cell is threatened but four walls are needed. Quarantined cells do not spread, and boundaries outside the grid do not need walls.

Source: Contain Virus on LeetCode. Use the original task for its coding environment and submissions.

Examples

# 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

# Example 2

Input
isInfected = [[1,1,1],[1,0,1],[1,1,1]]
Output
4

# 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

Constraints

m == isInfected.length
n == isInfected[i].length
1 <= m, n <= 50
isInfected[i][j] is either 0 or 1.
There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round.

Related LeetCode Problems

Practice more problems similar to Contain Virus.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.