Multi-source BFS from all initially spoiled cells simultaneously, that part came to me pretty fast.
This is a classic multi-source BFS problem: treat all initially spoiled fruits as sources and expand level by level, counting minutes. After BFS, check if any fresh fruit remains; if so, return -1, else return the number of minutes elapsed.
Pro tip: Mention that BFS is optimal because each minute corresponds to one level of expansion, and using a queue ensures we process all cells at the current minute before moving to the next. Also, note that you can optimize space by reusing the grid to mark visited cells.
Confirm grid dimensions, movement allowed (4-directional), and that spoilage spreads simultaneously. Model the problem as a graph where each cell is a node and edges connect adjacent cells.
Scan the grid to count fresh fruits and enqueue all spoiled fruit cells with their initial minute (0). Use a queue for BFS.
While the queue is not empty, process cells level by level (minute by minute). For each spoiled cell, check its 4 neighbors; if a neighbor is fresh, mark it spoiled, decrement fresh count, and enqueue it with minute+1.
After BFS, if fresh count > 0, return -1 (impossible). Otherwise, return the maximum minute reached (or minutes elapsed).
Time: O(m*n) since each cell is processed once. Space: O(m*n) for the queue in worst case (e.g., all spoiled initially).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.