<p>A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.</p>

<p>The world is modeled as an <code>m x n</code> binary grid <code>isInfected</code>, where <code>isInfected[i][j] == 0</code> represents uninfected cells, and <code>isInfected[i][j] == 1</code> represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two <strong>4-directionally</strong> adjacent cells, on the shared boundary.</p>

<p>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 <strong>will never be a tie</strong>.</p>

<p>Return <em>the number of walls used to quarantine all the infected regions</em>. If the world will become fully infected, return the number of walls used.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/01/virus11-grid.jpg" style="width: 500px; height: 255px;" />
<pre>
<strong>Input:</strong> 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]]
<strong>Output:</strong> 10
<strong>Explanation:</strong> 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:
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/01/virus12edited-grid.jpg" style="width: 500px; height: 257px;" />
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/01/virus13edited-grid.jpg" style="width: 500px; height: 261px;" />
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/01/virus2-grid.jpg" style="width: 653px; height: 253px;" />
<pre>
<strong>Input:</strong> isInfected = [[1,1,1],[1,0,1],[1,1,1]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> 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]]
<strong>Output:</strong> 13
<strong>Explanation:</strong> The region on the left only builds two new walls.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m ==&nbsp;isInfected.length</code></li>
	<li><code>n ==&nbsp;isInfected[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 50</code></li>
	<li><code>isInfected[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
	<li>There is always a contiguous viral region throughout the described process that will <strong>infect strictly more uncontaminated squares</strong> in the next round.</li>
</ul>

class Solution:
    def containVirus(self, isInfected: List[List[int]]) -> int:
        m, n = len(isInfected), len(isInfected[0])
        total_walls = 0
        
        def neighbors(i, j):
            for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
                if 0 <= x < m and 0 <= y < n:
                    yield x, y

        while True:
            regions = []
            visited = [[False] * n for _ in range(m)]
            
            # 1. Identify all regions of infection.
            for i in range(m):
                for j in range(n):
                    if isInfected[i][j] == 1 and not visited[i][j]:
                        stack = [(i, j)]
                        region = set()
                        borders = set()
                        walls_needed = 0
                        threatened = set()

                        while stack:
                            x, y = stack.pop()
                            if (x, y) in region:
                                continue
                            region.add((x, y))
                            visited[x][y] = True
                            
                            for nx, ny in neighbors(x, y):
                                if isInfected[nx][ny] == 0:
                                    walls_needed += 1
                                    threatened.add((nx, ny))
                                    borders.add((x, y))
                                elif isInfected[nx][ny] == 1 and not visited[nx][ny]:
                                    stack.append((nx, ny))

                        regions.append((region, threatened, walls_needed))
            
            if not regions:
                break

            # 2. Find the most threatening region.
            most_threatening = max(regions, key=lambda x: len(x[1]))

            # 3. Add walls to contain that region.
            total_walls += most_threatening[2]
            
            # 4. Update the grid: contain the most threatening region.
            for x, y in most_threatening[0]:
                isInfected[x][y] = -1  # Mark the region as contained

            # 5. Spread the virus in all other regions.
            for region, threatened, walls in regions:
                if region != most_threatening[0]:
                    for x, y in threatened:
                        isInfected[x][y] = 1  # Spread the virus

            # 6. If no other regions are left to contain, exit.
            if not any(len(threatened) > 0 for region, threatened, walls in regions):
                break

        return total_walls

17500