CodeArchon

mediumGraphsFacebookGoogle

Firewatch Distance

A fire marshal annotates every empty room with the shortest Manhattan distance to the nearest emergency exit (gate). Walls block paths.

Each cell is 0 (gate), -1 (wall), or INT_MAX (empty room). Fill empty rooms with the distance to the nearest gate.

Choose approach

2147483647
-1
0
2147483647
2147483647
2147483647
2147483647
-1
2147483647
-1
2147483647
-1
0
-1
2147483647
2147483647
1/10
Narrationstep 1 of 10

Seed BFS from every gate. Walls stay out.

1from collections import deque
2def wallsAndGates(rooms):
3 R, C = len(rooms), len(rooms[0])
4 q = deque()
5 for r in range(R):
6 for c in range(C):
7 if rooms[r][c] == 0: q.append((r, c))
8 while q:
9 r, c = q.popleft()
10 for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
11 nr, nc = r+dr, c+dc
12 if 0<=nr<R and 0<=nc<C and rooms[nr][nc] == 2**31 - 1:
13 rooms[nr][nc] = rooms[r][c] + 1
14 q.append((nr, nc))
Variables
gates=2

How to think about it

  1. Multi-source BFS = single BFS with multiple roots.
  2. First touch is cheapest in unweighted graphs.
  3. O(R·C) because each cell is enqueued once.

Edge cases to catch in interview

  • Isolated room -> stays INT_MAX.
  • No gates -> grid unchanged.

Examples

Example 1[[1,0]]
{"grid":[[2147483647,0]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed