Contain Virus - Problem
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] == 0represents uninfected cellsisInfected[i][j] == 1represents cells contaminated with the virus
A 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 (the affected area that threatens the most uninfected cells the following night).
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.
Input & Output
Example 1 — Basic Containment
$
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
💡 Note:
Two regions exist. Left region threatens 2 cells, right region threatens 4 cells. We contain the right region first with 10 walls, then the left spreads. Process continues until all contained.
Example 2 — Single Region
$
Input:
isInfected = [[1,1,1],[1,0,1],[1,1,1]]
›
Output:
4
💡 Note:
Single infected region surrounds one uninfected cell. We need 4 walls to completely isolate the center cell from infection.
Example 3 — No Infection
$
Input:
isInfected = [[0,0,0],[0,0,0],[0,0,0]]
›
Output:
0
💡 Note:
No infected cells exist, so no walls are needed.
Constraints
- m == isInfected.length
- n == isInfected[i].length
- 1 ≤ m, n ≤ 50
- isInfected[i][j] is either 0 or 1
- There will never be a tie for the region that threatens the most uninfected cells
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
2D binary grid with infected (1) and uninfected (0) cells
2
Find Regions
Use BFS to identify connected infected regions
3
Prioritize Threats
Count cells each region would infect next, contain the worst
Key Takeaway
🎯 Key Insight: Always contain the region threatening the most uninfected cells to minimize total wall usage
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code