Contain Virus

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 their 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, meaning the affected area, a 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.

Example 1
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
InputisInfected = [[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]]
Output10
There are 2 contaminated regions; quarantining the left region uses 5 walls on the first day, then quarantining the right region uses 5 more walls, for a total of 10.
Example 2
1 1 1
1 0 1
1 1 1
InputisInfected = [[1,1,1],[1,0,1],[1,1,1]]
Output4
Even though only one cell is saved, 4 walls are built on the shared boundaries around that cell.

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.

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate