KatInterview

Grid Contagion with Neighbor-Count Thresholds

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbfsgridsimulation

Last updated

Compute when each grid cell becomes infected under a synchronous neighbor-count rule, using a multi-source BFS that updates counts incrementally instead of rescanning each round.

Grid Contagion with Neighbor-Count Thresholds

A rectangular grid has m rows and n columns. Each cell (r, c) has a resistance value thresholds[r][c]: the minimum number of infected orthogonal neighbors (up, down, left, right) the cell needs before it becomes infected.

You are also given seeds, a list of (row, col) pairs for cells that are infected from the very start.

The infection advances in synchronous rounds:

  1. Round 0. Every cell listed in seeds is infected. In addition, every cell whose threshold is 0 is infected, even if it is not a seed.
  2. Round t >= 1. Every not-yet-infected cell that has at least thresholds[r][c] infected neighbors, counting only cells infected in rounds strictly before t, becomes infected in round t. Cells infected in round t do not help each other within round t.
  3. An infected cell stays infected forever and keeps counting toward its neighbors.

Return an m x n grid where each entry is the round in which that cell became infected, or -1 if it never becomes infected.

Notes:

  • seeds may be empty and may contain duplicate coordinates.
  • A seed is infected at round 0 regardless of its threshold.
  • A threshold larger than the number of in-grid neighbors of a cell means that cell can never be infected unless it is a seed.

Aim for roughly O(m * n) time. Re-scanning the whole grid every round is too slow when the infection travels along a long winding path.

Constraints

  • m == len(thresholds), n == len(thresholds[0])
  • 1 <= m, n <= 1000 and m * n <= 10^6
  • 0 <= thresholds[r][c] <= 4
  • 0 <= len(seeds) <= m * n
  • Every seed coordinate lies inside the grid.

Examples

Example 1

Input: spread_times([[2, 2, 2], [2, 2, 2], [2, 2, 2]], [[0, 0], [0, 2], [2, 0]])

Output: [[0, 1, 0], [1, 2, 3], [0, 3, 4]]

Example 2

Input: spread_times([[1, 0], [3, 1]], [])

Output: [[1, 0], [-1, 1]]

Hints

Hint 1

Think of each infection as an event that tells its neighbors 'one more of your neighbors is infected'. Rather than recounting from scratch each round, keep a running count per cell.

Hint 2

Start a BFS queue containing every round-0 cell (seeds and threshold-0 cells together). When you pop a cell infected at round t, bump the counter of each not-yet-infected neighbor.

Hint 3

When a neighbor's counter reaches its threshold, mark it infected at round t + 1 and enqueue it. Because the queue is FIFO and times only increase by 1, the round numbers come out correct. Never count toward cells that are already infected.