Walls and Gates
Problem
You are given a 2D grid, rooms, made up of m rows and n columns, representing the floor plan of a building. Each cell holds one of three possible values:
-1— a wall or an obstacle that cannot be passed through.0— a gate.2147483647(i.e.INT_MAX) — an empty room.
Starting from every empty room, you may move up, down, left, or right into an adjacent cell, but never diagonally, and never through a wall. Fill each empty room in the grid with the length of the shortest path from that room to its nearest gate. If a room cannot reach any gate at all, it should keep the value 2147483647.
Modify the grid in place — the function does not need to return anything, but the grid passed in should end up holding the final distances.
- There can be more than one gate on the grid, and a room only needs the distance to the closest one.
- Distance is measured in the number of moves between adjacent cells, not straight-line distance.
- Walls block movement entirely; you cannot pass through them or land on them.
Examples
Example 1:
Input: rooms = [[2147483647,-1,0],[2147483647,2147483647,2147483647],[2147483647,-1,2147483647]]
Output: [[3,-1,0],[2,2,1],[1,-1,2]]
Explanation:
- The grid is 3 rows by 3 columns, with a single gate at position
(0,2). - The wall at
(0,1)and the wall at(2,1)stay as-1and are never overwritten. - The room at
(1,2)is directly above... actually adjacent to the gate, so it becomes1; the room at(2,2)is two steps away, so it becomes2. - The room at
(0,0)must travel around the wall at(0,1), taking a path of length3through(1,0) -> (1,1) -> (1,2) -> (0,2).
Example 2:
Input: rooms = [[0,-1],[2147483647,2147483647]]
Output: [[0,-1],[1,2]]
Explanation:
- The single gate sits at
(0,0). - The cell at
(1,0)is adjacent to the gate, giving distance1. - The cell at
(1,1)cannot reach the gate directly (its neighbor(0,1)is a wall), so it must route through(1,0), giving distance2.
Example 3:
Input: rooms = [[2147483647]]
Output: [[2147483647]]
Explanation:
- There are no gates anywhere on the grid, so the single empty room has no path to any gate and keeps its original placeholder value.
Constraints
m == rooms.lengthn == rooms[i].length1 <= m, n <= 250rooms[i][j]is one of-1,0, or2147483647.
Solution
Sign in to get AI feedback on your answer. Your work is saved while you do.
Sign in to evaluate