My first instinct was to run BFS from each query point separately, which works fine for small inputs but falls apart when k is large.
Use multi-source BFS from all stores simultaneously to compute the shortest distance to the nearest store for every cell in O(m*n) time. Then answer each query in O(1) by looking up the precomputed distance, handling duplicates and unreachable cases. This approach scales efficiently for large query lists.
Pro tip: Mention that you can optimize memory by storing distances in a 2D array and reusing it for all queries, and that you can early-exit BFS if all reachable cells are covered. Also, discuss how to handle duplicate queries by caching results to avoid redundant lookups.
Confirm grid dimensions, cell types (walls, stores, empty), and query format. Discuss edge cases: no stores, empty query list, duplicate queries, isolated rooms, and unreachable cells.
Explain that multi-source BFS from all stores computes shortest distances to the nearest store for all cells in one pass, which is more efficient than running BFS per query.
Initialize a queue with all store coordinates, set their distance to 0, and perform BFS to fill a 2D distance array. Mark unreachable cells as -1.
For each query, return the precomputed distance from the distance matrix. Handle duplicates by caching results or simply returning the same value.
State time complexity O(m*n + q) and space O(m*n). Discuss trade-offs: precomputation cost vs. per-query cost, and suitability for large query lists.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.