Practice/Uber/Leetcode 749. Contain Virus
CodingOptional
You are given a 2D grid representing a geographic area where each cell is either infected (1) or uninfected (0). The infection spreads daily according to specific rules, and your task is to minimize the total damage by strategically building containment walls.
Spreading Mechanism:
Daily Containment Process:
Each day, before the infection spreads, you must:
Identify all distinct infected regions (connected components of infected cells)
For each region, calculate:
Select the region that threatens the most uninfected cells
Build walls around that selected region to permanently contain it
Allow all other regions to spread to their adjacent uninfected cells
This process repeats each day until no infected region can spread further.
Return the total number of walls built throughout the entire containment process.
m == isInfected.length (number of rows)n == isInfected[i].length (number of columns)isInfected[i][j] is either 0 or 1Example 1:
` 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: Day 1: Two regions exist.
Example 2:
Input: isInfected = [[1,1,1], [1,0,1], [1,1,1]] Output: 4 Explanation: One region surrounds a single uninfected cell in the center. The region threatens 1 cell and needs 4 walls (the four sides of the center cell). After building 4 walls, the center is protected and no further spreading occurs.
Example 3:
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: Multiple regions compete. The right region threatens more cells initially. Contain regions strategically over multiple days until all are contained or can't spread.