I knew it was BFS pretty fast, the multi-source part clicked quickly too.
Use multi-source BFS: initialize a queue with all source cells (value 1) and set their distances to 0. Then perform BFS level by level, updating each unvisited neighbor's distance as current distance + 1. If no sources exist, return a matrix filled with -1.
Pro tip: Mention that multi-source BFS is optimal because it processes each cell once, achieving O(m*n) time and space. Also, clarify that you handle the no-source case upfront to avoid unnecessary BFS.
Confirm that distance is Manhattan (4-directional) and that source cells have distance 0. Identify the edge case where there are no source cells, requiring all cells to be -1.
Select multi-source BFS because it efficiently computes shortest distances from multiple sources simultaneously. Avoid naive BFS from each cell, which would be O((m*n)^2).
Create a distance matrix initialized to -1 (or a large number) and a queue. Enqueue all source cells and set their distance to 0.
While the queue is not empty, dequeue a cell and explore its 4 neighbors. For each unvisited neighbor, set its distance to current distance + 1 and enqueue it.
After BFS, the distance matrix contains the shortest distances for all reachable cells. If no sources were found, the matrix remains all -1, which is correct.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.