750. Contain Virus
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to simulate a process of containing a virus on a 2D grid. Each day, we can build walls to quarantine exactly one connected region of infected cells. The choice of which region to quarantine is based on a specific rule: we must choose the region that threatens to infect the most new cells on the next day. After quarantining one region, all other infected regions spread to their adjacent uninfected cells. We need to calculate the total number of walls built until all viruses are contained.
Solution
Contain Virus in Python
import collections
class Solution:
def containVirus(self, isInfected: list[list[int]]) -> int:
m, n = len(isInfected), len(isInfected[0])
total_walls = 0
while True:
visited = set()
regions = []
# 1. Find all virus regions and their frontiers
for r in range(m):
for c in range(n):
if isInfected[r][c] == 1 and (r, c) not in visited:
# Start BFS to find a new region
component = set()
frontier = set()
perimeter = 0
q = collections.deque([(r, c)])
visited.add((r, c))
while q:
curr_r, curr_c = q.popleft()
component.add((curr_r, curr_c))
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nr, nc = curr_r + dr, curr_c + dc
if 0 <= nr < m and 0 <= nc < n:
if isInfected[nr][nc] == 0:
# Uninfected neighbor: part of frontier, needs a wall
frontier.add((nr, nc))
perimeter += 1
elif isInfected[nr][nc] == 1 and (nr, nc) not in visited:
# Infected neighbor: part of the same component
visited.add((nr, nc))
q.append((nr, nc))
if frontier:
regions.append({
'component': component,
'frontier': frontier,
'perimeter': perimeter
})
# 2. If no regions can spread, simulation ends
if not regions:
break
# 3. Find the most threatening region
regions.sort(key=lambda x: len(x['frontier']), reverse=True)
most_threatening = regions[0]
# 4. Add walls and quarantine the most threatening region
total_walls += most_threatening['perimeter']
for r_q, c_q in most_threatening['component']:
isInfected[r_q][c_q] = 2 # Mark as contained
# 5. Spread virus from other regions
for i in range(1, len(regions)):
for r_s, c_s in regions[i]['frontier']:
isInfected[r_s][c_s] = 1 # Spread virus
return total_walls
Contain Virus in Java
class Solution {
public int containVirus(int[][] isInfected) {
int m = isInfected.length;
int n = isInfected[0].length;
int totalWalls = 0;
while (true) {
boolean[][] visited = new boolean[m][n];
// Each list entry corresponds to one region's info
List<List<Integer>> regions = new ArrayList<>();
List<Set<Integer>> frontiers = new ArrayList<>();
List<Integer> perimeters = new ArrayList<>();
// 1. Find all virus regions and their frontiers using BFS
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (isInfected[i][j] == 1 && !visited[i][j]) {
List<Integer> currentRegion = new ArrayList<>();
Set<Integer> currentFrontier = new HashSet<>();
int currentPerimeter = 0;
Queue<Integer> q = new LinkedList<>();
int startCell = i * n + j;
q.offer(startCell);
visited[i][j] = true;
int[] dr = {0, 0, 1, -1};
int[] dc = {1, -1, 0, 0};
while (!q.isEmpty()) {
int cell = q.poll();
int r = cell / n;
int c = cell % n;
currentRegion.add(cell);
for (int k = 0; k < 4; k++) {
int nr = r + dr[k];
int nc = c + dc[k];
if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
if (isInfected[nr][nc] == 0) {
currentFrontier.add(nr * n + nc);
currentPerimeter++;
} else if (isInfected[nr][nc] == 1 && !visited[nr][nc]) {
visited[nr][nc] = true;
q.offer(nr * n + nc);
}
}
}
}
if (!currentFrontier.isEmpty()) {
regions.add(currentRegion);
frontiers.add(currentFrontier);
perimeters.add(currentPerimeter);
}
}
}
}
// 2. If no regions can spread, simulation ends
if (regions.isEmpty()) {
break;
}
// 3. Find the most threatening region (largest frontier)
int maxFrontierIndex = 0;
for (int i = 1; i < frontiers.size(); i++) {
if (frontiers.get(i).size() > frontiers.get(maxFrontierIndex).size()) {
maxFrontierIndex = i;
}
}
// 4. Add walls and quarantine the most threatening region
totalWalls += perimeters.get(maxFrontierIndex);
for (int cellHash : regions.get(maxFrontierIndex)) {
int r = cellHash / n;
int c = cellHash % n;
isInfected[r][c] = 2; // Mark as contained
}
// 5. Spread virus from other regions
for (int i = 0; i < regions.size(); i++) {
if (i == maxFrontierIndex) continue;
for (int cellHash : frontiers.get(i)) {
int r = cellHash / n;
int c = cellHash % n;
isInfected[r][c] = 1; // Spread virus
}
}
}
return totalWalls;
}
}
Contain Virus in C++
class Solution {
public:
int containVirus(vector<vector<int>>& isInfected) {
int m = isInfected.size();
int n = isInfected[0].size();
int totalWalls = 0;
while (true) {
vector<vector<bool>> visited(m, vector<bool>(n, false));
vector<vector<int>> regions; // Store infected cells for each region
vector<set<int>> frontiers; // Store frontier cells for each region
vector<int> perimeters; // Store perimeter for each region
// 1. Find all virus regions and their frontiers
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (isInfected[i][j] == 1 && !visited[i][j]) {
vector<int> currentRegion;
set<int> currentFrontier;
int currentPerimeter = 0;
queue<pair<int, int>> q;
q.push({i, j});
visited[i][j] = true;
int dr[] = {0, 0, 1, -1};
int dc[] = {1, -1, 0, 0};
while (!q.empty()) {
pair<int, int> cell = q.front();
q.pop();
int r = cell.first;
int c = cell.second;
currentRegion.push_back(r * n + c);
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k];
int nc = c + dc[k];
if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
if (isInfected[nr][nc] == 0) {
currentFrontier.insert(nr * n + nc);
currentPerimeter++;
} else if (isInfected[nr][nc] == 1 && !visited[nr][nc]) {
visited[nr][nc] = true;
q.push({nr, nc});
}
}
}
}
if (!currentFrontier.empty()) {
regions.push_back(currentRegion);
frontiers.push_back(currentFrontier);
perimeters.push_back(currentPerimeter);
}
}
}
}
// 2. If no regions can spread, simulation ends
if (regions.empty()) {
break;
}
// 3. Find the most threatening region
int maxFrontierIndex = 0;
for (int i = 1; i < frontiers.size(); ++i) {
if (frontiers[i].size() > frontiers[maxFrontierIndex].size()) {
maxFrontierIndex = i;
}
}
// 4. Add walls and quarantine the most threatening region
totalWalls += perimeters[maxFrontierIndex];
for (int cellHash : regions[maxFrontierIndex]) {
int r = cellHash / n;
int c = cellHash % n;
isInfected[r][c] = 2; // Mark as contained
}
// 5. Spread virus from other regions
for (int i = 0; i < regions.size(); ++i) {
if (i == maxFrontierIndex) continue;
for (int cellHash : frontiers[i]) {
int r = cellHash / n;
int c = cellHash % n;
isInfected[r][c] = 1; // Spread virus
}
}
}
return totalWalls;
}
};
Contain Virus in TypeScript
function containVirus(isInfected: number[][]): number {
const m = isInfected.length;
const n = isInfected[0].length;
let totalWalls = 0;
while (true) {
const visited: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false));
const regions: { component: [number, number][], frontier: Set<string>, perimeter: number }[] = [];
// 1. Find all virus regions and their frontiers
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
if (isInfected[r][c] === 1 && !visited[r][c]) {
const component: [number, number][] = [];
const frontier = new Set<string>();
let perimeter = 0;
const q: [number, number][] = [[r, c]];
visited[r][c] = true;
while (q.length > 0) {
const [currR, currC] = q.shift()!;
component.push([currR, currC]);
const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];
for (const [dr, dc] of directions) {
const nr = currR + dr;
const nc = currC + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
if (isInfected[nr][nc] === 0) {
frontier.add(`${nr},${nc}`);
perimeter++;
} else if (isInfected[nr][nc] === 1 && !visited[nr][nc]) {
visited[nr][nc] = true;
q.push([nr, nc]);
}
}
}
}
if (frontier.size > 0) {
regions.push({ component, frontier, perimeter });
}
}
}
}
// 2. If no regions can spread, simulation ends
if (regions.length === 0) {
break;
}
// 3. Find the most threatening region
let maxFrontierIndex = 0;
for (let i = 1; i < regions.length; i++) {
if (regions[i].frontier.size > regions[maxFrontierIndex].frontier.size) {
maxFrontierIndex = i;
}
}
const mostThreatening = regions[maxFrontierIndex];
// 4. Add walls and quarantine the most threatening region
totalWalls += mostThreatening.perimeter;
for (const [r_q, c_q] of mostThreatening.component) {
isInfected[r_q][c_q] = 2; // Mark as contained
}
// 5. Spread virus from other regions
for (let i = 0; i < regions.length; i++) {
if (i === maxFrontierIndex) continue;
for (const cellStr of regions[i].frontier) {
const [r_s, c_s] = cellStr.split(',').map(Number);
isInfected[r_s][c_s] = 1; // Spread virus
}
}
}
return totalWalls;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.