Paths Subjects Questions Quizzes Pricing Search
Intermediate Open Pro

Matrix Infection

You are given an m x n grid where each cell is one of:

  • 0: empty cell (never gets infected)
  • 1: healthy cell that can become infected
  • 2: already-infected cell

Every minute, any infected cell (2) infects its orthogonally adjacent healthy cells (1), turning them into 2 for the next minute. Return the minimum number of minutes that must pass until no cell is 1 (i.e., every reachable healthy cell has been infected). If it is impossible to infect every healthy cell, return -1.

Example 1

grid = [
  [2,1,1],
  [1,1,0],
  [0,1,1]
]

Output: 4

Example 2

grid = [
  [2,1,1],
  [0,1,1],
  [1,0,1]
]

Output: -1 (the bottom-left 1 is isolated by 0s and can never be reached).

Example 3

grid = [[0,2]]

Output: 0 (there are no healthy cells to infect).

Constraints

  • 1 <= m, n <= 10
  • Each cell is 0, 1, or 2.

Share this question

← Back to Graphs practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.