My first instinct was to BFS from each source separately and merge results, which works but is painfully slow if there are many sources.
Use multi-source BFS starting from all source cells simultaneously, treating the grid as an unweighted graph. Initialize a distance matrix with -1, set sources to 0, and enqueue them; then BFS level by level, updating distances for unvisited non-wall neighbors. This ensures each cell gets the shortest distance to any source in O(m*n) time.
Pro tip: Mention that multi-source BFS is equivalent to adding a virtual super-source connected to all sources, which elegantly handles the 'nearest' requirement and avoids redundant searches. Also, discuss how to handle edge cases like no sources or all walls.
Confirm grid dimensions, movement directions (4-directional), and what constitutes a source, target, and wall. Ask about input size to discuss time/space complexity trade-offs.
Select multi-source BFS using a queue. Initialize a distance matrix with -1, set source cells to 0, and enqueue them. Use a queue for BFS and consider a visited set or rely on distance matrix.
While queue is not empty, dequeue a cell, explore its 4 neighbors. If a neighbor is within bounds, not a wall, and has distance -1, set its distance to current distance + 1 and enqueue it.
After BFS, cells still at -1 are unreachable (or walls). Return the distance matrix, ensuring walls remain -1 or as specified.
State time complexity O(m*n) since each cell is processed once, and space O(m*n) for the queue and distance matrix. Discuss edge cases: no sources, all walls, single cell, large grid.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.