My first instinct was BFS and I went down that road for a few minutes before realizing the K-neighbor condition makes it way messier than standard BFS.
Model the problem as a multi-source BFS where each cell's infection time depends on when at least K neighbors are infected. Use a priority queue (min-heap) to process cells in order of infection time, updating neighbor counts and enqueueing cells when their infected neighbor count reaches K. After the process, check if any healthy cells remain; if so, they are unreachable.
Pro tip: Clarify that K is a global constant and that infection times are non-decreasing; using a priority queue ensures we process cells in the correct order, avoiding multiple passes. Also, mention that if K > 4, no cell can ever be infected unless initially infected.
Restate the problem: given an m x n grid with initially infected cells, each minute a healthy cell becomes infected if at least K of its 4-directional neighbors are already infected. Determine the minute when all reachable cells are infected, or identify cells that never become infected.
Use a multi-source BFS with a priority queue (min-heap) to simulate the infection spread. Each cell's infection time is the earliest minute when its infected neighbor count reaches K.
Initialize a queue with all initially infected cells at time 0. For each cell, maintain a count of infected neighbors. When a cell is infected, increment the neighbor count for its healthy neighbors; if a neighbor's count reaches K, compute its infection time (current time + 1) and push it into the priority queue.
Keep track of the maximum infection time encountered. After the queue is empty, scan the grid to see if any healthy cells remain. If so, they will never be infected; otherwise, return the maximum time.
Discuss time complexity O(mn log(mn)) due to heap operations, and space complexity O(mn). Handle edge cases: K > 4, no initially infected cells, all cells initially infected, and disconnected regions.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.