Ctrl K

Quarantine for Mould

Hard
A warehouse floor is split into cells and given as a rectangular table grid: 1 is a cell taken by mould and 0 is a clean one. A single partition can be placed between any two cells that share a side. Every night the mould moves from each affected cell into every clean side-neighbour that is not separated from it by a partition. Resources are tight: each day you can fence off only **one** patch, a group of affected cells connected through their sides. Every day you pick the patch that would infect the most clean cells the next night; partitions go on every border between it and clean cells, and that patch never grows again. That patch is guaranteed to be unique. The process goes on while there are patches that can still grow. Return the total number of partitions placed.
Example 1
grid=[[0, 0, 0], [0, 1, 0], [0, 0, 0]] → 4

A single patch in the centre borders four clean cells. On the first day we put 4 walls around it, and that is it.

Example 2
grid=[[1, 1, 0, 0, 0], [0, 0, 0, 0, 1]] → 6

The left patch threatens three cells, the right one two. On day one we seal the left patch (3 walls); overnight the right one grows into [[1, 1, 0, 0, 1], [0, 0, 0, 1, 1]]. On day two it needs 3 more walls, 6 in total.

Example 3
grid=[[1, 1], [1, 1]] → 0

There are no clean cells left to protect, so no walls are needed.

Constraints
  • 1 ≤ len(grid), len(grid[0]) ≤ 50
  • grid[i][j] is 0 or 1
  • Each day the patch threatening the most clean cells is unique
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsA Knight's Move Log MediumFrame Around an Ink Blot HardLongest Uphill Walk HardBall Into the Hole HardCrossing at High Tide Hard
loading Python…
Input
grid=[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 37 tests on the server, hidden ones included.