> For the complete documentation index, see [llms.txt](https://wentao-shao.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wentao-shao.gitbook.io/leetcode/graph-search/286.walls-and-gates.md).

# 286.Walls-and-Gates

## 286. Walls and Gates

## 题目地址

<https://leetcode.com/problems/walls-and-gates/>

## 题目描述

```
You are given a m x n 2D grid initialized with these three possible values.

-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

Example: 
Given the 2D grid:

INF  -1  0  INF
INF INF INF  -1
INF  -1 INF  -1
  0  -1 INF INF
After running your function, the 2D grid should be:

  3  -1   0   1
  2   2   1  -1
  1  -1   2  -1
  0  -1   3   4
```

## 代码

### Approach #1 Multi End BFS

```java
public static final int[] d = {0, 1, 0, -1, 0};

public void wallsAndGates(int[][] rooms) {
    if (rooms.length == 0) return;
    int m = rooms.length;
      int n = rooms[0].length;

    Deque<Integer> queue = new ArrayDeque<>();
    for (int i = 0; i < m; ++i)
        for (int j = 0; j < n; ++j)
            if (rooms[i][j] == 0) 
              queue.offer(i * n + j); // Put gates in the queue

    while (!queue.isEmpty()) {
        int x = queue.poll();
        int i = x / n, j = x % n;
        for (int k = 0; k < 4; ++k) {
            int p = i + d[k];
              int q = j + d[k + 1]; // empty room
            if (0 <= p && p < m && 0 <= q && q < n 
                && rooms[p][q] == Integer.MAX_VALUE) { // rooms[p][q] == Integer.MAX_VALUE

                rooms[p][q] = rooms[i][j] + 1;
                queue.offer(p * n + q);
            }
        }
    }
}
```

### Approach #2 Naive BFS

```java
public static final int[] d = {0, 1, 0, -1, 0};

public void wallsAndGates(int[][] rooms) {
    if (rooms.length == 0) return;
    for (int i = 0; i < rooms.length; ++i)
        for (int j = 0; j < rooms[0].length; ++j)
            if (rooms[i][j] == 0) 
              bfs(rooms, i, j);
}

private void bfs(int[][] rooms, int i, int j) {
    int m = rooms.length;
      int n = rooms[0].length;
    Deque<Integer> queue = new ArrayDeque<>();
    queue.offer(i * n + j); // Put gate in the queue
    while (!queue.isEmpty()) {
        int x = queue.poll();
        i = x / n; 
          j = x % n;
        for (int k = 0; k < 4; ++k) {
            int p = i + d[k];
              int q = j + d[k + 1];
            if (0 <= p && p < m && 0 <= q && q < n 
                && rooms[p][q] > rooms[i][j] + 1) { // rooms[p][q] > rooms[i][j] + 1

                rooms[p][q] = rooms[i][j] + 1;
                queue.offer(p * n + q);
            }
        }
    }
}
```

### Approach #3 DFS

```java
class Solution {
  int[] d = {0, 1, 0, -1, 0};

  public void wallsAndGates(int[][] rooms) {
    for (int i = 0; i < rooms.length; i++) {
      for (int j = 0; j < rooms[0].length; j++) {
        if (rooms[i][j] == 0) {
          dfs(rooms, i, j);
        }
      }
    }
  }

  public void dfs(int[][] rooms, int i, int j) {
    for (int k = 0; k < 5; k++) {
      int p = i + d[k];
      int q = j + d[k + 1];
      if (0 <= p && p < rooms.length 
          && 0 <= q && q < rooms[0].length 
          && rooms[p][q] > rooms[i][j] + 1) {

            rooms[p][q] = rooms[i][j] + 1;
            dfs(rooms, p, q);
        }
    }
  }

}
```

<https://leetcode.com/problems/walls-and-gates/discuss/72748/Benchmarks-of-DFS-and-BFS>


---

# 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://wentao-shao.gitbook.io/leetcode/graph-search/286.walls-and-gates.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.
