Skip to content

286. Walls and Gates 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
 public:
  void wallsAndGates(vector<vector<int>>& rooms) {
    constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    const int m = rooms.size();
    const int n = rooms[0].size();
    queue<pair<int, int>> q;

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (rooms[i][j] == 0)
          q.emplace(i, j);

    while (!q.empty()) {
      const auto [i, j] = q.front();
      q.pop();
      for (const auto& [dx, dy] : dirs) {
        const int x = i + dx;
        const int y = j + dy;
        if (x < 0 || x == m || y < 0 || y == n)
          continue;
        if (rooms[x][y] != INT_MAX)
          continue;
        rooms[x][y] = rooms[i][j] + 1;
        q.emplace(x, y);
      }
    }
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public void wallsAndGates(int[][] rooms) {
    final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    final int m = rooms.length;
    final int n = rooms[0].length;
    Queue<Pair<Integer, Integer>> q = new ArrayDeque<>();

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (rooms[i][j] == 0)
          q.offer(new Pair<>(i, j));

    while (!q.isEmpty()) {
      final int i = q.peek().getKey();
      final int j = q.poll().getValue();
      for (int[] dir : dirs) {
        final int x = i + dir[0];
        final int y = j + dir[1];
        if (x < 0 || x == m || y < 0 || y == n)
          continue;
        if (rooms[x][y] != Integer.MAX_VALUE)
          continue;
        rooms[x][y] = rooms[i][j] + 1;
        q.offer(new Pair<>(x, y));
      }
    }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
  def wallsAndGates(self, rooms: list[list[int]]) -> None:
    dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))
    kInf = 2**31 - 1
    m = len(rooms)
    n = len(rooms[0])
    q = collections.deque((i, j)
                          for i in range(m)
                          for j in range(n)
                          if rooms[i][j] == 0)

    while q:
      i, j = q.popleft()
      for dx, dy in dirs:
        x = i + dx
        y = j + dy
        if x < 0 or x == m or y < 0 or y == n:
          continue
        if rooms[x][y] != kInf:
          continue
        rooms[x][y] = rooms[i][j] + 1
        q.append((x, y))