Fill Rooms With Distance to Nearest Exit
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests multi-source BFS on a grid to propagate shortest walking distances from all exits simultaneously to every reachable empty room.
Fill Rooms With Distance to Nearest Exit
You are given a rectangular floor plan as a 2D grid of integers. Each cell holds one of three values:
-1— a wall (impassable)0— an exit2147483647— an empty room (written asINFbelow for readability)
Produce a new grid with the same dimensions. Copy walls and exits unchanged. For every empty room, replace INF with the shortest walking distance to the nearest exit, measured in steps along the four cardinal directions (up, down, left, right). Walls block movement. A room that cannot reach any exit must keep the value INF.
Movement is strictly 4-directional; diagonal moves are not allowed. Each step between adjacent non-wall cells counts as distance 1.
Constraints
0 <= rows, cols <= 250- The grid contains only the values
-1,0, or2147483647 - There may be zero exits, zero empty rooms, or both
- An empty room with no path to any exit retains
2147483647in the output - Do not modify the input grid; return a new grid
Examples
Example 1
Input: fill_rooms_with_exit_distances([[2147483647, -1, 0, 2147483647], [2147483647, 2147483647, 2147483647, -1], [2147483647, -1, 2147483647, -1], [0, -1, 2147483647, 2147483647]])
Output: [[3, -1, 0, 1], [2, 2, 1, -1], [1, -1, 2, -1], [0, -1, 3, 4]]
Hints
Hint 1
Instead of searching from each room outward, think about what happens if you start the search from every exit at the same time.
Hint 2
A standard BFS explores cells in non-decreasing order of distance. The first time a cell is reached, that distance is already the shortest — no need to revisit it.
Hint 3
You can tell whether a cell has already been assigned a distance by checking whether its value is still INF. Use this to avoid a separate visited structure.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Multi-Source BFS from All Exits
Core Idea
The straightforward approach — run a BFS from every empty room to find its nearest exit — repeats work for every room and costs O((m·n)²) in the worst case.
The key insight is to reverse the direction of the search. Load every exit into a queue at distance 0 and run a single BFS that fans outward from all of them simultaneously. You can think of this as a virtual "super-exit" with a zero-cost edge to each real exit. Because BFS expands cells in non-decreasing order of distance, the very first time the wavefront reaches a room is via the shortest possible path to any exit. The distance is written once and the cell is never enqueued again.
A separate visited set is unnecessary. A cell still holding INF has not been reached yet, so that value itself serves as the "unvisited" marker. Any cell with another value is a wall, an exit, or already has its final distance.
Why It Is Correct
BFS maintains the invariant that the queue holds cells at distance d followed by cells at distance d+1. Starting all exits at distance 0:
- A room is assigned
d+1only when it is first discovered from a neighbor at distanced. No shorter path can exist — if one did, that neighbor would have been processed earlier and the room would already be marked. - Every room reachable from at least one exit is eventually reached, because BFS exhausts the entire connected region.
- Rooms that are fully walled off are never discovered, so they keep
INF, which matches the spec.
Edge Cases
- Empty input or no rows: return an empty list immediately.
- No exits in the grid: the queue starts empty and all rooms stay
INF. - No rooms (only walls and exits): the BFS runs but finds nothing to update.
- Rooms surrounded by walls: they are never reached and remain
INF. - Multiple exits at equal distance from a room: BFS naturally records the correct minimum without any explicit tie-breaking.
Complexity
- Time: O(m·n) — each cell is enqueued at most once (exits at startup, rooms on first discovery) and each dequeue inspects 4 neighbors.
- Space: O(m·n) — for the output grid copy and the BFS queue, which in the worst case holds every cell.
Reference Solution
from collections import deque
from typing import List
def fill_rooms_with_exit_distances(rooms: List[List[int]]) -> List[List[int]]:
if not rooms:
return []
result = [row[:] for row in rooms]
rows = len(result)
cols = len(result[0]) if rows else 0
INF = 2147483647
# Seed the queue with every exit at distance 0
queue = deque()
for r in range(rows):
for c in range(cols):
if result[r][c] == 0:
queue.append((r, c))
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
# Multi-source BFS: first arrival at any INF cell is the shortest distance
while queue:
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and result[nr][nc] == INF:
result[nr][nc] = result[r][c] + 1
queue.append((nr, nc))
return result
Common Mistakes to Avoid
- Running a separate BFS per exit. This gives O(k·m·n) time and produces wrong answers unless you also take the per-cell minimum across runs.
- Marking cells visited on dequeue instead of enqueue. The same
INFcell will be pushed multiple times before it is first processed, exploding the queue size and producing incorrect distances. - Using DFS. DFS does not visit cells in distance order, so it cannot guarantee the first path found is the shortest one.