Shortest Distance from All Buildings (BFS)
You are given a grid of 0s, 1s, and 2s. Find an empty land (0) that has the shortest total travel distance to all buildings (1s). This is a multi-source shortest path problem using BFS.
Why Interviewers Ask This
Meta evaluates candidates on their ability to optimize graph traversal in constrained environments. This problem tests if you can handle multi-source BFS efficiently without redundant calculations, ensuring the solution scales with grid size while managing memory usage for distance accumulation.
How to Answer This Question
1. Clarify constraints: Ask about grid dimensions and whether buildings are reachable from all empty lands. 2. Define the core strategy: Explain that running BFS from every building is better than from every empty land to avoid repeated traversals of the same nodes. 3. Outline the algorithm: Describe iterating through each building, performing a level-order BFS to record distances to reachable empty lands, and accumulating these distances in a separate matrix. 4. Discuss optimization: Mention checking reachability (ensuring all buildings can reach a spot) and pruning paths that exceed current minimums. 5. Analyze complexity: State the time complexity as O(M*N*Buildings) and space complexity as O(M*N) for storing distances and visited states. 6. Validate edge cases: Address scenarios with no valid empty land or unreachable buildings.
Key Points to Cover
- Running BFS from each building is more efficient than from each empty land
- Using a visit count matrix to verify all buildings can reach a specific location
- Accumulating distances in a separate matrix during traversal to avoid re-computation
- Handling edge cases where no valid meeting point exists or buildings are isolated
- Explicitly stating time and space complexity relative to grid dimensions
Sample Answer
To solve this, I would first clarify the input constraints, specifically the maximum grid size and whether we assume connectivity. My approach involves a reverse BFS strategy. Instead of starting from every empty land, which could be inefficient, I will iterate through each building marked as '1'. For every building, I'll perform a Breadth-First Search to calculate the shortest distance to all reachable empty lands '0', accumulating these distances in a global sum matrix. Crucially, I will also maintain a visit count matrix to ensure that any candidate empty land has been reached by all buildings; if a land cell hasn't been visited by every building, it cannot be a valid solution. After processing all buildings, I will scan the sum matrix to find the minimum value among cells where the visit count equals the total number of buildings. If no such cell exists, I return -1. This method ensures we only traverse the grid once per building rather than per empty land, optimizing performance significantly. For example, in a 3x3 grid with two buildings, we run two BFS passes. The first pass adds distances from Building A, the second from Building B. We then check which zero-cell has the lowest total sum and was visited twice. This aligns well with Meta's focus on scalable algorithms for large-scale data structures.
Common Mistakes to Avoid
- Attempting to run BFS from every empty land, leading to Time Limit Exceeded errors on large grids
- Failing to track which buildings have reached a specific cell, resulting in invalid solutions
- Ignoring obstacles (2s) during BFS traversal, causing incorrect path calculations
- Not handling the case where multiple buildings exist but cannot reach any common empty land
Practice This Question with AI
Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.
Related Interview Questions
Convert Binary Tree to Doubly Linked List in Place
Hard
MicrosoftWord Ladder (BFS)
Hard
MetaDesign a Set with $O(1)$ `insert`, `remove`, and `check`
Easy
CiscoFind K Closest Elements (Heaps)
Medium
MetaShould Meta launch a paid, ad-free version of Instagram?
Hard
MetaProduct Strategy for a 'Lite' Version of an App
Medium
Meta