← Snowflake Interview Insights
My first instinct was to BFS from each desk individually and that works but it's slow if you have a lot of desks.
Use multi-source BFS starting from all bathroom cells simultaneously to compute the shortest distance to the nearest bathroom for every cell. Then construct the result matrix by placing the computed distances for desk cells and -1 for unreachable desks.
Pro tip: Mention that multi-source BFS is optimal because it processes each cell once, achieving O(m*n) time, and discuss how to handle edge cases like no bathrooms or desks surrounded by walls.
Clarify that the grid contains desks, bathrooms, and empty cells, and that movement is only up/down/left/right. Confirm that we need distances for desks only, with -1 for unreachable desks.
Select multi-source BFS because it efficiently computes shortest paths from multiple sources (bathrooms) in unweighted grids. Explain why BFS is preferred over running BFS from each desk.
Enqueue all bathroom cells with distance 0, then perform BFS level by level, updating distances for each visited cell. Use a distance matrix initialized to -1 or infinity.
Iterate through the grid: for each desk cell, output its computed distance (or -1 if unreachable); for non-desk cells, output 0 or any placeholder as specified.
State time and space complexity: O(m*n) time and O(m*n) space. Discuss edge cases: no bathrooms, no desks, desks already adjacent to bathrooms, and disconnected components.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.