Grid Containment: Minimum Removals to Stop Spread
Trees & GraphsModel answerLast updated
Find the fewest cells to remove from a grid to prevent infection from spreading to healthy neighbors.
You're analyzing a rectangular grid where each cell is either healthy (represented as 0) or currently infected (represented as 1).
The infection behaves according to these rules:
- During each discrete time step, every infected cell simultaneously spreads to all orthogonally adjacent healthy cells (up, down, left, right)
- Infected cells eventually become inactive after a fixed duration, but this happens after they've had opportunities to spread
- Diagonal neighbors are not affected
You can intervene by removing any number of cells at the very beginning (before any spreading occurs). A removed cell cannot spread infection or become infected.
Write a function that determines the minimum number of cells you must remove at the start to guarantee the infection never spreads to any currently healthy cell. After your removals, existing infections will eventually burn out and the grid will stabilize.
Function Signature:
def min_removals(grid: List[List[int]]) -> int:
pass
Input:
grid: A 2D list wheregrid[r][c]is either 0 (healthy) or 1 (infected)1 <= rows, cols <= 20
Output:
- An integer representing the minimum number of cells to remove
Example 1:
Input: grid = [[0, 1],
[0, 0]]
Output: 1
Explanation: The infected cell at position (0,1) is adjacent to two healthy cells. Removing that single infected cell prevents any spread.
Example 2:
Input: grid = [[1, 0, 1]]
Output: 1
Explanation: The middle healthy cell is adjacent to both infected cells. Removing just that one healthy cell isolates the two infections from each other (though they have no healthy cells to spread to anyway).
Example 3:
Input: grid = [[0, 0],
[0, 0]]
Output: 0
Explanation: No infected cells exist, so no intervention needed.
Hints
Hint 1
Think about which pairs of cells represent potential infection paths that must be blocked
Hint 2
This is fundamentally a graph problem where you need to 'cut' certain connections between two groups
Hint 3
In bipartite graphs, there's a classical theorem relating minimum vertex covers to maximum matchings
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Problem Interpretation
Before diving into the solution, clarify the goal with your interviewer. The problem asks to prevent infection from spreading to healthy cells, not to kill every cell. This means:
- We want to ensure no healthy cell ever becomes infected
- Existing infections will eventually die out on their own
- The grid reaches a stable state where no further changes occur
This interpretation aligns with the examples and makes the problem tractable.
Approach: Bipartite Matching
Modeling as a Graph Problem
Create a bipartite graph:
- Left partition: all currently infected cells
- Right partition: all currently healthy cells
- Edges: connect an infected cell to a healthy cell if they are orthogonally adjacent
An edge represents a potential infection path that will activate at the first time step. For the infection to be contained, at least one endpoint of every edge must be removed. This is precisely the definition of a vertex cover.
Why Bipartite Matching Works
By König's theorem, in a bipartite graph, the size of the minimum vertex cover equals the size of the maximum matching. Computing a maximum matching is efficient and gives us the answer directly.
Correctness reasoning:
- If any edge has both endpoints present, infection will spread across it—so we need a vertex cover
- If we remove a vertex cover, no infection paths remain—so a cover is sufficient
- The minimum cover equals the maximum matching size in bipartite graphs—giving us optimality
Why This Beats Brute Force
With up to 400 cells, trying all removal subsets (2^400 possibilities) is completely infeasible. Recognizing the graph structure reduces this to a polynomial-time matching problem.
Algorithm: Augmenting Paths
Use Kuhn's algorithm (also called the Hungarian algorithm for bipartite matching):
- Build the bipartite graph from the grid
- Iterate through infected cells, trying to find augmenting paths
- An augmenting path alternates between unmatched and matched edges
- Each successful augmentation increases the matching size by 1
- Return the final matching size
Complexity Analysis
- Time: O(V · E) where V is the number of cells (up to 400) and E is the number of edges (at most 4V). This gives roughly 640,000 operations, well within limits. Can be improved to O(E√V) with Hopcroft-Karp.
- Space: O(V + E) for adjacency lists and matching structure
Edge Cases
- No infected cells: Return 0 (nothing to contain)
- No healthy cells: Return 0 (no edges exist)
- Isolated infections: Infected cells with no healthy neighbors contribute no edges
- Bottleneck cells: A single healthy cell adjacent to multiple infections—matching correctly returns 1
Implementation
from typing import List
def min_removals(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
# Build bipartite graph: infected cells -> adjacent healthy cells
infected_to_healthy = {}
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1:
continue
infected_id = r * cols + c
adjacent_healthy = []
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0:
healthy_id = nr * cols + nc
adjacent_healthy.append(healthy_id)
if adjacent_healthy:
infected_to_healthy[infected_id] = adjacent_healthy
# Find maximum matching using augmenting paths
healthy_match = {} # maps healthy cell -> infected cell it's matched to
def find_augmenting_path(infected_id: int, visited: set) -> bool:
for healthy_id in infected_to_healthy[infected_id]:
if healthy_id in visited:
continue
visited.add(healthy_id)
# If this healthy cell is unmatched, or we can recursively
# find an augmenting path from its current match
if healthy_id not in healthy_match or \
find_augmenting_path(healthy_match[healthy_id], visited):
healthy_match[healthy_id] = infected_id
return True
return False
matching_size = 0
for infected_id in infected_to_healthy:
if find_augmenting_path(infected_id, set()):
matching_size += 1
return matching_size
Common Mistakes
-
Trying to simulate time steps: The problem doesn't require simulation. Since infections spread in the first time step regardless of their duration, containment is determined entirely by the initial graph structure.
-
Greedy removal of all infected cells: This often removes far more than necessary. A single strategic removal can block multiple infection paths.
-
Not recognizing the bipartite structure: Treating this as a general graph problem or trying backtracking will lead to inefficient solutions.
-
Forgetting diagonal cells aren't adjacent: Only orthogonal neighbors (4-connectivity) matter.
Follow-Up Extensions
If asked about larger grids (1000×1000): Use Hopcroft-Karp or model as max-flow (source → infected → healthy → sink with unit capacities). Decompose into connected components for parallelization.
If asked about incremental removal (one cell per time step instead of all at once): This becomes the NP-hard Firefighter problem. Timing and duration matter significantly. Use BFS/IDA* for small instances or greedy heuristics for larger ones.