#749
Hard Algorithms Contain virus
Array Depth-First Search Breadth-First Search Matrix Simulation
54.4% acceptance
Feb 21, 2026
441
466
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.
Solution
Rust
Time O(n * m)
Space O(n * m)
/*
* 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.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.
*/
use std::collections::{HashSet, VecDeque};
impl Solution {
pub fn contain_virus(mut is_infected: Vec<Vec<i32>>) -> i32 {
let (m, n) = (is_infected.len(), is_infected[0].len());
let dirs = [(0i32, 1i32), (0, -1), (1, 0), (-1, 0)];
let mut total_walls = 0;
loop {
let mut visited = vec![vec![false; n]; m];
let mut regions: Vec<(Vec<(usize, usize)>, HashSet<(usize, usize)>, i32)> = vec![];
for i in 0..m {
for j in 0..n {
if is_infected[i][j] == 1 && !visited[i][j] {
let mut cells = vec![];
let mut threatened: HashSet<(usize, usize)> = HashSet::new();
let mut walls = 0i32;
let mut q = VecDeque::new();
q.push_back((i, j));
visited[i][j] = true;
while let Some((r, c)) = q.pop_front() {
cells.push((r, c));
for &(dr, dc) in &dirs {
let (nr, nc) = (r as i32 + dr, c as i32 + dc);
if nr < 0 || nr >= m as i32 || nc < 0 || nc >= n as i32 { continue; }
let (nr, nc) = (nr as usize, nc as usize);
if is_infected[nr][nc] == 1 && !visited[nr][nc] {
visited[nr][nc] = true;
q.push_back((nr, nc));
} else if is_infected[nr][nc] == 0 {
threatened.insert((nr, nc));
walls += 1;
}
}
}
regions.push((cells, threatened, walls));
}
}
}
if regions.is_empty() || regions.iter().all(|(_, t, _)| t.is_empty()) {
break;
}
let max_idx = regions.iter().enumerate()
.max_by_key(|(_, (_, t, _))| t.len())
.map(|(i, _)| i)
.unwrap();
total_walls += regions[max_idx].2;
for &(r, c) in ®ions[max_idx].0 {
is_infected[r][c] = -1;
}
for (i, (_, threatened, _)) in regions.iter().enumerate() {
if i == max_idx { continue; }
for &(r, c) in threatened {
if is_infected[r][c] == 0 {
is_infected[r][c] = 1;
}
}
}
}
total_walls
}
}