Skip to content
RED SAGSkills
medium30 ptsbfsmatrix

Minutes Until the Rack Is Infected

A server room is a grid. Each cell is 0 (empty slot), 1 (healthy server) or 2 (infected server). Every minute, each infected server infects the healthy servers directly above, below, left and right of it.

Return the number of minutes until no healthy server remains. If some healthy server can never be reached, return -1. If there are no healthy servers at the start, return 0.

Example 1

Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Explanation: The infection takes 4 minutes to reach the bottom-right server.

Example 2

Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The bottom-left server is cut off.

Constraints

  • 1 <= rows, cols <= 200
  • grid[r][c] is 0, 1 or 2
Hint 1

Start a breadth-first search from all infected servers at once.

Hint 2

Each BFS layer is one minute; count the healthy servers so you know when you are done.

Discussion 0

Join free to post in the discussion.

Good practice for: Site Reliability Engineer, DevOps Engineer, Backend Developer, Cloud Engineer, Game Developer

Run checks your code on 3 sample tests. Submit runs all 9 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.