Solve BFS grid delivery routing
Company: DoorDash
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in grid-based graph traversal and shortest-path computation, along with complexity analysis and handling dynamic changes, assessing skills in algorithm design, graph algorithms, and data structures within the Coding & Algorithms domain.
Constraints
- 1 <= m, n (the grid may be empty; an empty grid returns []).
- Each cell is one of 'S', 'H', '.', '#'.
- There may be zero or more stores and zero or more homes.
- Movement is 4-directional (up/down/left/right); diagonal moves are not allowed.
- '#' cells are impassable; 'S', 'H', and '.' cells are all traversable.
- Distances are returned in row-major order of the home cells.
Examples
Input: ([['S', '.', 'H'], ['#', '.', '#'], ['H', '.', '.']],)
Expected Output: [2, 4]
Explanation: Home at (0,2) reaches store (0,0) via (0,0)->(0,1)->(0,2) = 2 steps. Home at (2,0) must go (2,0)->(2,1)->(1,1)->(0,1)->(0,0) = 4 steps (the obstacles at (1,0) and (1,2) block the shorter routes).
Input: ([['S', 'H']],)
Expected Output: [1]
Explanation: The home is directly adjacent to the store, so distance 1.
Input: ([['H', '#', 'S']],)
Expected Output: [-1]
Explanation: The obstacle at (0,1) walls the home off from the store, so it is unreachable: -1.
Input: ([['S', '.', '.', 'H'], ['#', '#', '#', '.'], ['H', '.', '.', '.']],)
Expected Output: [3, 8]
Explanation: Home (0,3) is 3 steps along the top row. Home (2,0) is sealed off from the top except through column 3: (0,0)->(0,1)->(0,2)->(0,3)->(1,3)->(2,3)->(2,2)->(2,1)->(2,0) = 8 steps.
Input: ([['H']],)
Expected Output: [-1]
Explanation: A lone home with no store anywhere in the grid: unreachable, -1.
Input: ([],)
Expected Output: []
Explanation: Empty grid has no homes, so the answer is an empty array.
Input: ([['S', 'S', 'H'], ['H', '.', '.']],)
Expected Output: [1, 1]
Explanation: Multi-source BFS from both stores: home (0,2) is adjacent to store (0,1) = 1, and home (1,0) is adjacent to store (0,0) = 1. Homes are listed in row-major order: (0,2) then (1,0).
Hints
- Instead of running a separate BFS from each home, run ONE multi-source BFS seeded from all store cells at distance 0 at once. The first time BFS reaches a cell, that is its shortest distance to the closest store.
- Use a distance matrix initialized to -1 to double as the 'visited' marker: a cell with dist == -1 has not been reached yet, so unreachable homes naturally keep -1.
- After BFS fills the reachable region, scan the grid in row-major order (row by row, left to right) and append dist[i][j] for every 'H' cell to build the answer in the required order.