LeetCode 286, Medium. Topics: Array, Breadth-First Search, Matrix. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 17 parametrized pytest cases, and a playground notebook:
Problem
You are given a m × n 2D grid initialized with these three possible values:
-1 - A wall or obstacle that can not be traversed.
0 - A gate.
INF - Infinity an empty room. We use the value 2^31 - 1 = 2147483647 to represent INF.
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.
Follow up: Can you solve it in-place and in O(m × n) time complexity?
Examples
Explanation: the 2D grid is:
the result is:
explanation: the gate is located at (0,2), (3,0), (3,3). the room at (0,0) is distance 3 from the nearest gate at (3,0).
Constraints
m == rooms.length
n == rooms[i].length
1 <= m, n <= 100
rooms[i][j] is one of -1, 0, or 2147483647.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode 150, NeetCode 250, NeetCode All. Last modified on September 7, 2026