> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Shortest Distance from All Buildings

> Tested Python solution for LeetCode 317 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 317, [Hard](/catalog/hard). Topics: [Breadth-First Search](/catalog/topics/breadth-first-search), [Array](/catalog/topics/array), [Matrix](/catalog/topics/matrix). [View on LeetCode](https://leetcode.com/problems/shortest-distance-from-all-buildings/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 317   # by problem number
lcpy gen -s shortest_distance_from_all_buildings   # by problem name
```

## Problem

You are given an `m x n` grid `grid` of values `0`, `1`, or `2`, where:

* each `0` marks **an empty land** that you can pass by freely,
* each `1` marks **a building** that you cannot pass through, and
* each `2` 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.

### Examples

![Example 1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0317.Shortest%20Distance%20from%20All%20Buildings/images/buildings-grid.jpg)

```
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.
```

```
Input: grid = [[1,0]]
Output: 1
```

```
Input: grid = [[1]]
Output: -1
```

### Constraints

* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 50`
* `grid[i][j]` is either `0`, `1`, or `2`.
* There will be **at least one** building in the `grid`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/shortest_distance_from_all_buildings/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/shortest_distance_from_all_buildings/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque


class Solution:
    # Time: O(b * m * n) — one BFS per building (b = building count)
    # Space: O(m * n)
    def shortest_distance(self, grid: list[list[int]]) -> int:
        m, n = len(grid), len(grid[0])
        total = [[0] * n for _ in range(m)]
        reach = [[0] * n for _ in range(m)]
        building_count = sum(row.count(1) for row in grid)

        for i in range(m):
            for j in range(n):
                if grid[i][j] != 1:
                    continue
                distance = [[-1] * n for _ in range(m)]
                distance[i][j] = 0
                queue: deque[tuple[int, int]] = deque([(i, j)])
                while queue:
                    r, c = queue.popleft()
                    for x, y in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
                        if 0 <= x < m and 0 <= y < n and grid[x][y] == 0 and distance[x][y] < 0:
                            distance[x][y] = distance[r][c] + 1
                            queue.append((x, y))
                for r in range(m):
                    for c in range(n):
                        if distance[r][c] >= 0:
                            total[r][c] += distance[r][c]
                            reach[r][c] += 1

        best = -1
        for i in range(m):
            for j in range(n):
                if (
                    grid[i][j] == 0
                    and reach[i][j] == building_count
                    and (best < 0 or total[i][j] < best)
                ):
                    best = total[i][j]
        return best
```

## Complexity

| Time | Space |
| - | - |
| O(b \* m \* n) — one BFS per building (b = building count) | O(m \* n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.