> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/breadth-first-search/317-shortest-distance-from-all-buildings.md).

# 317 Shortest Distance from All Buildings

## 317. [Shortest Distance from All Buildings](https://leetcode.com/problems/shortest-distance-from-all-buildings/description/)

## 1. Question

You want to build a house on anemptyland which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values **0**, **1** or **2**, where:

* Each **0** marks an empty land which you can pass by freely.
* Each **1** marks a building which you cannot pass through.
* Each **2** marks an obstacle which you cannot pass through.

For example, given three buildings at`(0,0)`,`(0,4)`,`(2,2)`, and an obstacle at`(0,2)`:

```
1 - 0 - 2 - 0 - 1
|   |   |   |   |
0 - 0 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 1 - 0 - 0
```

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.

**Note:**\
There will be at least one building. If it is not possible to build such house according to the above rules, return -1.

## 2. Implementation

**(1) BFS**

```java
class Solution {
    public int shortestDistance(int[][] grid) {
        if (grid == null || grid.length == 0) {
            return -1;
        }

        int m = grid.length;
        int n = grid[0].length;

        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        int[][] distance = new int[m][n];
        int[][] reach = new int[m][n];

        int buildings = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    ++buildings;
                    getDistanceByBFS(i, j, distance, reach, directions, grid);
                }
            }
        }

        int res = Integer.MAX_VALUE;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 0 && reach[i][j] == buildings) {
                    res = Math.min(res, distance[i][j]);
                }
            }
        }
        return res == Integer.MAX_VALUE ? -1 : res;
    }

    public void getDistanceByBFS(int row, int col, int[][] distance, int[][] reach, int[][] directions, int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;

        boolean[][] visited = new boolean[m][n];

        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[] {row, col});

        int dist = 0;

        while (!queue.isEmpty()) {
            ++dist;
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                int[] curCell = queue.remove();

                for (int[] direction : directions) {
                    int nextRow = curCell[0] + direction[0];
                    int nextCol = curCell[1] + direction[1];

                    if (isValid(nextRow, nextCol, visited, grid)) {
                        distance[nextRow][nextCol] += dist;
                        reach[nextRow][nextCol] += 1;
                        queue.add(new int[] {nextRow, nextCol});
                        visited[nextRow][nextCol] = true;
                    }
                }
            }
        }
    }

    public boolean isValid(int row, int col, boolean[][] visited, int[][] grid) {
        return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && !visited[row][col] && grid[row][col] == 0;
    }
}
```

## 3. Time & Space Complexity

**BFS:** 时间复杂度O(M^2N^2),BFS的时间复杂度是O(mn), 总的时间复杂度是 O(# of buildings ) \* O(mn), 最坏的情况是每个cell都是building， 总的时间复杂度为O(mn) \* O(mn) => O(m^2n^2), 空间复杂度O(mn)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/breadth-first-search/317-shortest-distance-from-all-buildings.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
