Minimum Removals to Contain Grid Blight

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

An agricultural plot is represented as an R x C grid where each cell holds an integer state at t = 0:

  • 0 — Healthy crop
  • 1 — Infected crop
  • 2 — Dead (cleared or inert soil)

Time advances in discrete steps t = 1, 2, ... under these rules:

  1. During each step, every currently Infected (1) cell transmits the blight to all orthogonally adjacent (up, down, left, right) Healthy (0) cells.
  2. Any crop that becomes newly infected on step t begins its own infectious window on step t + 1.
  3. Every Infected cell stays infectious for K steps in total and then permanently turns Dead (2).
  4. Dead (2) cells remain 2 forever and neither spread nor contract the blight.

Before step 1 starts (at t = 0), you may intervene by clearing any chosen subset of cells — whether currently 0 or 1 — immediately setting their state to 2.

Implement min_interventions(grid: List[List[int]], K: int) -> int to return the smallest number of cells that must be set to 2 at t = 0 so that no cell left in state 0 at t = 0 ever becomes infected during the outbreak.

def min_interventions(grid: List[List[int]], K: int) -> int:
    ...

Examples

Example 1

Input:  grid = [[1, 0, 0],
                [0, 0, 2]], K = 3
Output: 1

Clearing the lone infected crop at (0, 0) turns it into 2 before step 1, leaving zero active sources so none of the four healthy cells ever catch the blight.

Example 2

Input:  grid = [[1, 0, 1],
                [2, 1, 2]], K = 2
Output: 1

Cell (0, 1) is the only healthy crop and borders three infected cells (0, 0), (0, 2), and (1, 1). Clearing (0, 1) alone (1 intervention) acts as a preemptive removal and beats clearing all three infected neighbors (3 interventions).

Example 3

Input:  grid = [[0, 1, 0, 2, 1],
                [2, 0, 2, 1, 0]], K = 5
Output: 2

Dead cells at (0, 3) and (1, 2) split the plot into two independent zones. On the left, infected (0, 1) borders three healthy crops; on the right, healthy (1, 4) borders two infected crops. Clearing (0, 1) and (1, 4) stops all spread in 2 interventions, whereas clearing only infected cells costs 3 and clearing only healthy cells costs 4.

Constraints

  • 1 <= R, C <= 20 (an empty grid has 0 conflicts and returns 0)
  • grid[r][c] is 0, 1, or 2
  • 1 <= K <= 10

Step-by-step walkthrough

  1. Restate the rules and goal

    Let us pin down the rules before choosing an algorithm:

    • grid has R rows and C columns (1 <= R, C <= 20), where 0 = Healthy, 1 = Infected, and 2 = Dead.
    • Clearing a cell at t = 0 sets its value to 2 before step 1 starts. We may clear either an Infected cell (eliminating an active source) or a Healthy cell (digging a firebreak so nothing can catch or cross there).
    • During each step, every currently Infected cell spreads to its orthogonal (up, down, left, right) Healthy neighbors, and each Infected cell expires into 2 after K steps (1 <= K <= 10).
    • Goal: find the smallest number of cells to clear at t = 0 so zero cells that remain 0 at t = 0 ever catch the blight.
    Example 1 (K = 3):
    Before t = 0 clearance:  [ 1  0  0 ]    Clear (0, 0) -> [ 2  0  0 ]
                             [ 0  0  2 ]                    [ 0  0  2 ]
    Zero Infected cells remain, so none of the four Healthy cells ever become infected -> return 1.
    
  2. Why exhaustive subset simulation times out

    A brute-force approach tests subsets of 0 cells, 1 cell, 2 cells, and so on, simulating the outbreak step by step until a subset prevents all spread.

    Why is that infeasible at 20 x 20? With 400 cells, there are 2^400 subsets — even checking subsets of size 10 requires C(400, 10) ≈ 2.6 × 10^19 simulations. Exhaustive search works only on tiny 3 x 3 test grids; to handle 20 x 20 instantaneously, we need to examine when the first transmission happens.

  3. Key insight: step 1 decides everything, so `K` cancels out

    Suppose an Infected cell u (1) borders a Healthy cell v (0) at t = 0, and we clear neither cell. Because K >= 1, u is guaranteed to be active during step 1, so u immediately infects v on step 1!

    Now look at the converse: suppose we clear enough cells at t = 0 so that no adjacent (Infected, Healthy) pair survives anywhere on the grid.

    At t = 0 (after clearance): zero Infected (1) cells border any Healthy (0) cell.
      -> Step 1: zero Healthy cells touch an Infected neighbor, so 0 new infections occur!
      -> Steps 2..K: active Infected cells only age out as timers reach 0, so still 0 new infections!
      -> Step K: all surviving initial Infected cells turn Dead (2). Outbreak finished!
    

    Therefore, preventing all future spread is 100% equivalent to breaking every orthogonal (1, 0) neighbor pair at t = 0. Notice that K (1 <= K <= 10) never alters the answer because any unbroken pair already fails on step 1.

  4. Model conflicts as a bipartite vertex cover

    Translate the grid into a conflict graph:

    • Nodes: grid cells.
    • Conflict edges: connect two orthogonally adjacent cells whenever one is 1 (Infected) and the other is 0 (Healthy). Dead cells (2), (1, 1) pairs, and (0, 0) pairs produce zero edges.

    Choosing the fewest nodes so every edge touches at least one chosen node is a minimum vertex cover.

    Why can we not simply clear all conflicted Infected cells, or all conflicted Healthy cells? Look at Example 3:

    Example 3 (# means Dead = 2):
      col: 0 1 2 3 4
    row 0: 0 1 0 # 1    Left zone:  Infected (0, 1) borders 3 Healthy cells
    row 1: # 0 # 1 0    Right zone: Healthy (1, 4) borders 2 Infected cells
    
    - Clear only Infected cells: 1 (left) + 2 (right) = 3 clearances
    - Clear only Healthy cells:  3 (left) + 1 (right) = 4 clearances
    - Mix both sides: clear Infected (0, 1) + Healthy (1, 4) = 2 clearances!
    

    Every conflict edge joins an Infected cell (1) to a Healthy cell (0). A graph whose nodes divide into two groups with edges only between the groups (never within the same group) is a bipartite graph.

  5. König's theorem: minimum vertex cover = maximum matching

    Although minimum vertex cover is NP-hard on arbitrary graphs, König's theorem makes it polynomial on any bipartite graph:

    size of a minimum vertex cover  =  size of a maximum matching
    

    A matching is a set of conflict edges that share no endpoints (disjoint one-to-one (Infected, Healthy) pairs).

    • Why cover >= matching is clear: M completely disjoint conflict pairs share zero cells, so any valid plan must spend at least 1 clearance on each pair — at least M in total.
    • What König's theorem adds: on a bipartite graph, a valid vertex cover of size M always exists, so computing the maximum matching size directly returns min_interventions!
  6. Build the conflict adjacency map

    Scan the R x C grid once and map each Infected cell (r, c) to its orthogonally adjacent Healthy cells (nr, nc). Infected cells with no Healthy neighbors cannot cause conflicts and are omitted.

    from typing import Dict, List, Set, Tuple
    
    Cell = Tuple[int, int]
    DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1))
    
    
    def build_edges(grid: List[List[int]]) -> Dict[Cell, List[Cell]]:
        """Map each Infected cell (1) to its adjacent Healthy cells (0)."""
        rows = len(grid)
        cols = len(grid[0]) if rows > 0 else 0
        # edges: {(r, c): [(nr, nc), ...]} — Infected cells with zero Healthy neighbors are omitted.
        edges: Dict[Cell, List[Cell]] = {}
    
        for r in range(rows):
            for c in range(cols):
                # Only Infected cells (state 1) can initiate spread at step 1; Dead (2) cells act as walls.
                if grid[r][c] != 1:
                    continue
    
                healthy_neighbors: List[Cell] = []
                for dr, dc in DIRECTIONS:
                    nr = r + dr
                    nc = c + dc
                    # Bounds check uses 0 <= nr < rows and 0 <= nc < cols to stay inside the R x C grid.
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0:
                        healthy_neighbors.append((nr, nc))
    
                if healthy_neighbors:
                    edges[(r, c)] = healthy_neighbors
    
        return edges
    
  7. Find the maximum matching via Kuhn's augmenting-path DFS

    Maintain matched_to, a dictionary mapping each claimed healthy cell to the infected cell currently paired with it:

    1. For each infected cell, inspect its healthy neighbors one by one.
    2. If healthy is unclaimed (current_owner is None), pair them immediately (matching_size += 1).
    3. If healthy is already claimed by current_owner, recursively ask try_augment(current_owner, ...) whether current_owner can shift to an alternative Healthy neighbor so infected can take healthy.

    That chain of reassignments is an augmenting path. Within a single outer DFS, seen_healthy prevents revisiting the same Healthy cell so cycles never cause infinite recursion.

    def try_augment(
        infected: Cell,
        edges: Dict[Cell, List[Cell]],
        matched_to: Dict[Cell, Cell],
        seen_healthy: Set[Cell],
    ) -> bool:
        """Try to pair `infected` with a Healthy neighbor, rearranging existing pairs if needed."""
        for healthy in edges[infected]:
            # Skip Healthy cells already explored during this single DFS attempt to avoid infinite loops.
            if healthy in seen_healthy:
                continue
            seen_healthy.add(healthy)
    
            current_owner = matched_to.get(healthy)
            # Either `healthy` is unmatched, or `current_owner` can recursively move to a different Healthy cell.
            if current_owner is None or try_augment(current_owner, edges, matched_to, seen_healthy):
                matched_to[healthy] = infected
                return True
    
        return False
    

    Trace Kuhn's algorithm on Example 3 ([[0, 1, 0, 2, 1], [2, 0, 2, 1, 0]]):

    Edges:
      (0, 1) -> [(1, 1), (0, 2), (0, 0)]
      (0, 4) -> [(1, 4)]
      (1, 3) -> [(1, 4)]
    
    1. Try (0, 1): (1, 1) is free -> matched_to[(1, 1)] = (0, 1)        (matching_size = 1)
    2. Try (0, 4): (1, 4) is free -> matched_to[(1, 4)] = (0, 4)        (matching_size = 2)
    3. Try (1, 3): wants (1, 4), currently owned by (0, 4).
         Ask (0, 4) to move: its only neighbor (1, 4) is in seen_healthy -> False.
         (1, 3) has no other neighbors -> False                         (matching_size = 2)
    
    Return 2 (matching the optimal 2-cell cover {(0, 1), (1, 4)}).
    
  8. Complete solution

    Combining min_interventions, build_edges, and try_augment yields the full implementation. Because R * C <= 400, at most 200 pairs can exist simultaneously, bounding recursion depth at 201.

    from typing import Dict, List, Set, Tuple
    
    Cell = Tuple[int, int]
    DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1))
    
    
    def min_interventions(grid: List[List[int]], K: int) -> int:
        """Return the fewest plants to remove (set to Dead) at t = 0 so that the
        infection never reaches a plant that is Healthy at t = 0.
        """
        # Phase 1: Build the bipartite conflict graph between Infected (1) and Healthy (0) neighbors.
        # Because K >= 1, any unremoved Infected plant infects every unremoved Healthy neighbor at step 1.
        # If we break all (Infected, Healthy) neighbor pairs at t = 0, zero plants ever catch the infection.
        # edges: {(r, c): [(nr, nc), ...]} mapping each Infected cell to its adjacent Healthy cells.
        edges = build_edges(grid)
    
        # Phase 2: Find the maximum bipartite matching using Kuhn's augmenting-path algorithm.
        # By Konig's theorem, minimum vertex cover size == maximum matching size on a bipartite graph.
        # matched_to: {healthy_cell: infected_cell} storing which Infected cell currently claims each Healthy cell.
        matched_to: Dict[Cell, Cell] = {}
        matching_size = 0
    
        for infected in edges:
            # Use a fresh `seen` set per starting `infected` cell so cells visited in earlier
            # failed searches can still be used along newly opened alternating paths.
            seen_healthy: Set[Cell] = set()
            if try_augment(infected, edges, matched_to, seen_healthy):
                matching_size += 1
    
        return matching_size
    
    
    def build_edges(grid: List[List[int]]) -> Dict[Cell, List[Cell]]:
        """Map each Infected cell (1) to its adjacent Healthy cells (0)."""
        rows = len(grid)
        cols = len(grid[0]) if rows > 0 else 0
        # edges: {(r, c): [(nr, nc), ...]} — Infected cells with zero Healthy neighbors are omitted.
        edges: Dict[Cell, List[Cell]] = {}
    
        for r in range(rows):
            for c in range(cols):
                # Only Infected cells (state 1) can initiate spread at step 1; Dead (2) cells act as walls.
                if grid[r][c] != 1:
                    continue
    
                healthy_neighbors: List[Cell] = []
                for dr, dc in DIRECTIONS:
                    nr = r + dr
                    nc = c + dc
                    # Bounds check uses 0 <= nr < rows and 0 <= nc < cols to stay inside the R x C grid.
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0:
                        healthy_neighbors.append((nr, nc))
    
                if healthy_neighbors:
                    edges[(r, c)] = healthy_neighbors
    
        return edges
    
    
    def try_augment(
        infected: Cell,
        edges: Dict[Cell, List[Cell]],
        matched_to: Dict[Cell, Cell],
        seen_healthy: Set[Cell],
    ) -> bool:
        """Try to pair `infected` with a Healthy neighbor, rearranging existing pairs if needed."""
        for healthy in edges[infected]:
            # Skip Healthy cells already explored during this single DFS attempt to avoid infinite loops.
            if healthy in seen_healthy:
                continue
            seen_healthy.add(healthy)
    
            current_owner = matched_to.get(healthy)
            # Either `healthy` is unmatched, or `current_owner` can recursively move to a different Healthy cell.
            if current_owner is None or try_augment(current_owner, edges, matched_to, seen_healthy):
                matched_to[healthy] = infected
                return True
    
        return False
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture embers (1 = Infected) sitting beside dry stalks (0 = Healthy) on a field where bare dirt (2 = Dead) cannot burn. Before step 1 starts, you can clear either embers or dry stalks (turning them into dirt 2) so that no remaining dry stalk ever catches fire. Because K >= 1, any uncleared ember stays active during step 1 and immediately ignites every orthogonally adjacent uncleared stalk; conversely, if zero (1, 0) neighbor pairs survive at t = 0, nothing new catches on step 1 or any later step, and the initial embers simply die out after K steps.

Trying all subsets of cells to clear and simulating each outbreak fails rapidly: a 20 x 20 plot has 400 cells (2^400 subsets, with C(400, 10) ≈ 2.6 × 10^19 subsets of size 10 alone). Simple heuristics such as clearing only Infected cells, clearing only Healthy cells, or greedily deleting whichever cell touches the most conflicts also fail whenever the optimal containment mixes clearing Infected hubs in one region and Healthy firebreaks in another.

Instead, add a conflict edge between every orthogonally adjacent (Infected, Healthy) pair. Selecting the fewest nodes so every edge has at least one selected endpoint is a minimum vertex cover (the smallest node set touching every edge). Because every conflict edge links a 1 on one side to a 0 on the other, this conflict graph is a bipartite graph (a graph whose vertices split into two disjoint sets with edges only between the sets). By König's theorem (which states that on any bipartite graph, the minimum vertex cover has the exact same size as the maximum matching), we only need to compute a maximum matching (the largest collection of non-overlapping one-to-one (Infected, Healthy) edges).

Trace Example 3 on grid = [[0, 1, 0, 2, 1], [2, 0, 2, 1, 0]]:

  1. Left conflict edges connect Infected (0, 1) to Healthy (0, 0), (0, 2), and (1, 1); right conflict edges connect Infected (0, 4) and (1, 3) to Healthy (1, 4).
  2. Kuhn's algorithm (which pairs left-side nodes one by one using an augmenting path — an alternating chain of swaps that frees up a partner for the incoming node) pairs (0, 1) -> (1, 1) (size 1) and (0, 4) -> (1, 4) (size 2).
  3. Next, (1, 3) asks for (1, 4) (held by (0, 4)), which cannot move anywhere else. Maximum matching size = 2 (matching the mixed 2-cell clearance {(0, 1), (1, 4)}).

Complexity

Let V = R × C <= 400 be the number of cells in grid and E be the number of orthogonal (Infected, Healthy) conflict pairs (E < 2V on a 4-connected grid).

  • Time: O(V^2) — Building edges inspects each of the V cells and up to 4 orthogonal neighbors once in O(V) time. Kuhn's algorithm then launches at most V depth-first searches (one per Infected cell with conflicts), and seen_healthy guarantees each search visits every Healthy cell and conflict edge at most once (O(V + E) = O(V) work per search), totaling O(V^2) operations.
  • Space: O(V) — Storing edges (O(V + E) = O(V)), matched_to (at most V / 2 pairs), seen_healthy (at most V cells), and the recursion stack (at most V / 2 + 1 <= 201 frames) all grow linearly with V.

Edge cases

  • All Healthy, all Infected, or all Dead grids: edges is empty because no 1 touches a 0, immediately returning 0.
  • Empty grid []: Handled cleanly (cols = 0), returning 0.
  • Dead cells (2) acting as natural barriers (e.g., [[1, 2, 0]]): State 2 blocks orthogonal contact, generating zero edges and returning 0.
  • One Healthy cell surrounded by Infected cells (Example 2): All conflict edges share that single Healthy cell, so maximum matching size is 1.
  • Varying K (1 <= K <= 10): Every K >= 1 yields the exact same minimum clearance count because any surviving (1, 0) pair already spreads on step 1.

Common mistakes

  • Clearing only Infected cells (or only Healthy cells): Taking min(#conflicted infected, #conflicted healthy) fails on grids like Example 3 (returning 3 instead of 2) whenever one region has an Infected hub and another has a Healthy hub.
  • Greedy highest-degree removal: Repeatedly clearing the cell with the most remaining conflicts fails on a plus-shaped cluster (a degree-4 Healthy center surrounded by 4 Infected arms that each touch 1 outer Healthy tip), spending 5 clearances instead of clearing the 4 Infected arms.
  • Sharing one seen_healthy set across all outer loop iterations: After an augmenting swap updates matched_to, Healthy cells visited in an earlier failed search can become part of a newly opened path; reusing seen_healthy misses valid pairs and undercounts.
  • Including diagonal neighbors: Blight spreads strictly up, down, left, and right (4 directions, not 8).

Alternative approaches

  • Minimum cut / maximum flow: Construct a directed flow network with source -> infected (capacity 1), infected -> healthy (capacity infinity), and healthy -> sink (capacity 1). By the max-flow min-cut theorem, the minimum s-t cut equals the minimum vertex cover, and setting source/sink edge capacities to cost[r][c] naturally solves weighted cell-clearance costs.
  • Hopcroft–Karp bipartite matching: Finds shortest augmenting paths in breadth-first layers before augmenting multiple vertex-disjoint paths per phase in O(E × sqrt(V)) time; overkill for V <= 400, where Kuhn's short DFS finishes in microseconds, but ideal for massive grids.

Follow-up questions

  • Suppose you can clear at most one cell per time step while the blight continues spreading, instead of making every intervention at t = 0. How does the problem change? Now both step-by-step timing and K matter: while you clear one cell before step 1, every other Infected cell spreads simultaneously, so widely separated outbreaks may be impossible to contain without losing some Healthy crops. This becomes the firefighter problem (a graph-containment problem where one vertex is protected per round to minimize total burned vertices), which is NP-hard even on trees. On small grids, you would search over (grid_state, remaining_timers) states using branch and bound (pruning search branches whose already-infected count exceeds the best containment found so far) with state memoization.
  • How would you scale your algorithm if the field grew to 1,000 by 1,000 cells? At V = 10^6 and E ≈ 2 × 10^6, Kuhn's O(V × E) worst case and recursive DFS would time out or hit Python's recursion limit. Switch to an iterative Hopcroft–Karp solver (O(E × sqrt(V))), index only boundary cells (cells adjacent to the opposite state) as compact integers 0..B-1 in flat arrays, initialize a greedy maximal matching in one O(E) pass to shrink augmenting work, and solve disconnected boundary components independently in parallel.
  • How would your strategy adapt if transmission were probabilistic and decayed with distance rather than guaranteed across immediate neighbors? An Infected cell active for K steps directly infects a Healthy cell at distance d with cumulative probability 1 - (1 - p(d))^K (plus multi-hop cascade risk). If zero infection probability is permitted (p(d) > 0 forbidden), every threatened pair still links an initial 1 to an initial 0, keeping the conflict graph bipartite so maximum matching remains exact. Under a nonzero risk budget (such as keeping expected new infections <= tau), K and multi-hop chains matter again, so you would estimate expected spread via Monte Carlo simulation (averaging outcomes over many random trials) and select clearances via greedy marginal-risk reduction or beam search, validating the chosen set on independent holdout rollouts.

Follow-up questions

Similar questions

More OpenAI interview questions

All 493 OpenAI questions →