Skip to content
Veltoryx Technologies
ProProblem 110● MediumLeetCode #286 ↗3 min readUpdated 30 October 2026

Walls and Gates

Fill empty rooms with the distance to the nearest gate using multi-source BFS.

01The problem

You are given an m x n grid rooms initialized with three possible values:

  • -1: A wall or an obstacle.
  • 0: A gate.
  • INF: 2147483647 (empty room).

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.

Input (INF = 2147483647)OutputWhy
[[INF, -1, 0, INF], [INF, INF, INF, -1], [INF, -1, INF, -1], [0, -1, INF, INF]][[3, -1, 0, 1], [2, 2, 1, -1], [1, -1, 2, -1], [0, -1, 3, 4]]Each room filled with distance to closest gate.

Constraints

  • m == rooms.length
  • n == rooms[i].length
  • 1 <= m, n <= 250
  • rooms[i][j] is -1, 0, or 2^31 - 1.

Loading the rest of the lesson…