You are given an m x n grid grid of values 0, 1, or 2, where:
0 marks an empty land that you can pass by freely,1 marks a building that you cannot pass through, and2 marks an obstacle that you cannot pass through.You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right.
Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1.
The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
Example 1:
Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] Output: 7 Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2). The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.
Example 2:
Input: grid = [[1,0]] Output: 1
Example 3:
Input: grid = [[1]] Output: -1
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 50grid[i][j] is either 0, 1, or 2.grid.Problem Overview: You are given a grid with buildings (1), empty land (0), and obstacles (2). The goal is to choose an empty cell where building a house results in the minimum total travel distance to every building. Movement is allowed in four directions, and obstacles block paths.
Approach 1: BFS from Every Empty Land (Brute Force) (Time: O((mn)^2), Space: O(mn))
Iterate through the grid and treat every empty cell as a potential house location. For each empty cell, run a Breadth-First Search to compute the distance to every building. BFS guarantees the shortest path in an unweighted grid. While exploring neighbors, accumulate the distance whenever a building is reached. If all buildings are reachable, update the global minimum.
This approach works because BFS explores the grid level by level, ensuring shortest path distances. The drawback is repeated traversal of the entire grid for every empty cell. In dense grids with many empty cells, this becomes expensive since each BFS costs O(mn).
Approach 2: BFS from Each Building (Optimal) (Time: O(kmn), Space: O(mn))
A more efficient strategy reverses the search direction. Instead of starting BFS from empty land, start BFS from each building. During traversal, update two matrices: one that accumulates total distance to each empty cell and another that counts how many buildings can reach that cell.
For every building, perform BFS across the matrix. When visiting an empty cell, add the current distance to its cumulative sum and increment its reachable-building counter. After processing all buildings, scan the grid and select the empty cell whose reachable-building count equals the total number of buildings and whose distance sum is minimal.
This works because BFS from each building computes shortest distances once per building rather than once per empty cell. The grid is traversed k times where k is the number of buildings, producing a total complexity of O(kmn). Distance aggregation avoids recomputation and keeps the solution scalable even for larger grids.
Recommended for interviews: The BFS-from-buildings approach is what interviewers expect. It demonstrates strong understanding of array grid traversal and BFS optimization. Mentioning the brute force solution first shows problem exploration, while transitioning to the building-based BFS shows algorithmic improvement and awareness of time complexity tradeoffs.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| BFS from Every Empty Land | O((mn)^2) | O(mn) | Useful for understanding the problem or when the grid has very few empty cells. |
| BFS from Each Building (Distance Accumulation) | O(kmn) | O(mn) | General optimal solution. Efficient when buildings are fewer than empty cells. |
| Multi-pass Grid BFS with Distance + Reach Counters | O(kmn) | O(mn) | Preferred implementation pattern for interviews and production-style grid problems. |
LeetCode 317. Shortest Distance from All Buildings Explanation and Solution • happygirlzt • 14,154 views views
Watch 9 more video solutions →Practice Shortest Distance from All Buildings with our built-in code editor and test cases.
Practice on FleetCode