KatInterview

Grid Containment: Minimum Removals to Stop Spread

Trees & GraphsModel answer
MediumModel answerTrees & Graphsbipartite-matchinggraph-theorygrid

Last 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 where grid[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