The key thing I almost missed was seeding all taxi positions into the queue at once before starting BFS.
Use multi-source BFS starting from all taxi positions simultaneously to compute shortest distances to every cell in O(mn) time. Initialize a distance matrix with -1 (unvisited) and enqueue all taxis with distance 0, then process level by level.
Pro tip: Mention that multi-source BFS is optimal because it explores each cell once, and discuss how to handle edge cases like no taxis or all taxis. Also, note that you can avoid a separate visited array by using the distance matrix itself.
Confirm grid dimensions, taxi representation (e.g., 1 for taxi, 0 for empty), and that distance is Manhattan (4-directional). Ask about edge cases like no taxis.
Select multi-source BFS over alternatives like running BFS from each taxi (O(k*mn)) or dynamic programming (which may not handle obstacles). Explain why BFS is optimal for unweighted grids.
Create a distance matrix initialized to -1, and a queue. Enqueue all taxi positions with distance 0 and set their distance in the matrix to 0.
While the queue is not empty, dequeue a cell, explore its 4 neighbors. If a neighbor is within bounds and unvisited (distance -1), set its distance to current distance + 1 and enqueue it.
After BFS, the distance matrix contains shortest distances. Return it. State time complexity O(mn) and space complexity O(mn) for the queue and distance matrix.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.