> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Contain Virus Python Solution with Tests

> Tested Python solution for LeetCode 749 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 749, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Matrix](/catalog/topics/matrix), [Simulation](/catalog/topics/simulation). [View on LeetCode](https://leetcode.com/problems/contain-virus/description/).

Generate this problem as a practice environment: tested reference solution, 16 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 749   # by problem number
lcpy gen -s contain_virus   # by problem name
```

## Problem

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.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/06/01/virus11-grid.jpg)

```
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:
![Example 1 after day 1](https://assets.leetcode.com/uploads/2021/06/01/virus12edited-grid.jpg)
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
![Example 1 after day 2](https://assets.leetcode.com/uploads/2021/06/01/virus13edited-grid.jpg)
```

![Example 2](https://assets.leetcode.com/uploads/2021/06/01/virus2-grid.jpg)

```
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.
```

```
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.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/contain_virus/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/contain_virus/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O((m * n)^2) across all days
    # Space: O(m * n)
    def contain_virus(self, is_infected: list[list[int]]) -> int:
        grid = is_infected
        rows, cols = len(grid), len(grid[0])
        walls_used = 0

        while True:
            seen = [[False] * cols for _ in range(rows)]
            regions: list[tuple[list[tuple[int, int]], set[tuple[int, int]], int]] = []
            for r in range(rows):
                for c in range(cols):
                    if grid[r][c] == 1 and not seen[r][c]:
                        seen[r][c] = True
                        stack = [(r, c)]
                        cells: list[tuple[int, int]] = []
                        fronts: set[tuple[int, int]] = set()
                        walls = 0
                        while stack:
                            x, y = stack.pop()
                            cells.append((x, y))
                            for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                                nx, ny = x + dx, y + dy
                                if 0 <= nx < rows and 0 <= ny < cols:
                                    if grid[nx][ny] == 0:
                                        walls += 1
                                        fronts.add((nx, ny))
                                    elif grid[nx][ny] == 1 and not seen[nx][ny]:
                                        seen[nx][ny] = True
                                        stack.append((nx, ny))
                        regions.append((cells, fronts, walls))

            if not regions:
                break
            max_threat = max(len(fronts) for _, fronts, _ in regions)
            if max_threat == 0:
                break
            target = next(region for region in regions if len(region[1]) == max_threat)
            walls_used += target[2]
            for x, y in target[0]:
                grid[x][y] = -1
            for cells, fronts, _ in regions:
                if cells is not target[0]:
                    for x, y in fronts:
                        grid[x][y] = 1

        return walls_used
```

## Complexity

| Time | Space |
| - | - |
| O((m \* n)^2) across all days | O(m \* n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.