Shortest Evacuation Route Through a Burning Building
Trees & GraphsAuto-graded · 16 test casesLast updated
Tests BFS shortest-path reasoning on a grid with time-dependent obstacles, requiring candidates to track fire spread and find the minimum escape steps simultaneously.
Shortest Evacuation Route Through a Burning Building
You are given a grid representing a building floor plan. A person starts at a fixed position and must reach any cell on the border of the grid. The building is on fire: fire spreads outward one cell per time step (4-directional), and the person also moves one cell per time step (4-directional).
The person cannot enter a cell that is on fire at the moment they would step into it. Fire spreads and the person moves simultaneously each tick: fire that was at distance d from any fire-source at time 0 will occupy new cells at time d. The person occupying a cell at time t is safe only if the fire does not reach that cell until strictly after time t.
Formally, let fire_time[r][c] be the earliest time step at which fire reaches cell (r, c) (starting from all fire cells simultaneously at time 0). The person may occupy cell (r, c) at time t only if t < fire_time[r][c] (the cell is not yet on fire when the person arrives).
Grid cell values:
0— open floor (passable)1— wall (impassable, fire does not spread through walls)2— fire source (fire starts here at time0)3— the person's starting position (treated as open floor for movement and fire-spread purposes)
Goal: Return the minimum number of steps for the person to reach any border cell, or -1 if it is impossible.
A border cell is any cell in row 0, row R-1, column 0, or column C-1, where R and C are the grid dimensions.
If the person starts on a border cell and that cell is safe at time 0, the answer is 0.
Notes:
- Fire does not spread through walls (
1cells). - There is exactly one
3in the grid. - There may be zero or more
2cells. - If a fire source itself is on the border, it is already burning and not a valid exit.
Constraints
1 <= R, C <= 100(grid dimensions)grid[i][j] ∈ {0, 1, 2, 3}- Exactly one cell contains
3. - The grid contains at least one cell.
- There is no constraint on the number of fire sources (may be zero).
- If the starting cell is on fire at time
0(a2is at that position — this won't occur per the cell definitions, but fire_time of the start is always> 0since it is a3cell treated as open floor, so the person is safe at time0).
Examples
Example 1
Input: min_evacuation_steps([[3, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 2, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]])
Output: 0
Example 2
Input: min_evacuation_steps([[2, 0, 0], [0, 1, 0], [0, 0, 3]])
Output: 0
Example 3
Input: min_evacuation_steps([[3]])
Output: 0
Hints
Hint 1
Run a multi-source BFS from all fire cells simultaneously to precompute fire_time[r][c] for every cell — this tells you the earliest tick fire arrives at each cell.
Hint 2
Then run a standard BFS from the person's start position, tracking the time step. When considering moving to neighbor (nr, nc) at time t+1, only enqueue it if t+1 < fire_time[nr][nc].
Hint 3
Remember to handle the case of zero fire sources separately: fire_time is effectively infinity everywhere, so it reduces to a plain shortest-path BFS. Also check whether the start is already on the border (answer = 0).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
This problem requires two coordinated BFS passes:
-
Multi-source BFS for fire propagation — precompute
fire_time[r][c], the earliest tick at which fire reaches each open cell, treating all fire sources as simultaneously enqueued at time0. Walls block fire spread. -
Single-source BFS for the person — standard BFS from the start, but when considering moving to
(nr, nc)at timet+1, the move is only valid ift+1 < fire_time[nr][nc](the cell hasn't burned yet when the person steps in).
Why It Is Correct
- Fire_time from multi-source BFS gives the exact moment fire enters each cell (BFS on an unweighted graph gives shortest/earliest distances).
- The person's BFS explores states
(row, col, time)in FIFO order, so the first time a border cell is dequeued, it corresponds to the minimum number of steps. The constraintt+1 < fire_time[nr][nc]correctly gates movement: equality means fire and person arrive simultaneously, which is forbidden. - Walls are treated symmetrically: neither the person nor fire can traverse them.
Edge Cases
- No fire sources:
fire_timestaysINFeverywhere, reducing to plain BFS. - Start on border: immediately return
0(person is already out). - Person surrounded by fire immediately: the BFS queue empties without reaching a border, return
-1. - 1×1 grid: the single cell is both start and border, so answer is
0.
Complexity
- Time: O(R × C) for both BFS passes.
- Space: O(R × C) for
fire_timeandvisitedarrays plus the BFS queues.
from typing import List
from collections import deque
def min_evacuation_steps(grid: List[List[int]]) -> int:
R = len(grid)
C = len(grid[0])
INF = float('inf')
start = None
fire_sources = []
for r in range(R):
for c in range(C):
if grid[r][c] == 3:
start = (r, c)
elif grid[r][c] == 2:
fire_sources.append((r, c))
# Multi-source BFS: compute fire arrival time at each cell
fire_time = [[INF] * C for _ in range(R)]
dq = deque()
for (fr, fc) in fire_sources:
fire_time[fr][fc] = 0
dq.append((fr, fc, 0))
while dq:
r, c, t = dq.popleft()
for dr, dc in [(-1,0),(1,0),(0,-1),(0,1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] != 1:
if fire_time[nr][nc] == INF:
fire_time[nr][nc] = t + 1
dq.append((nr, nc, t + 1))
sr, sc = start
def is_border(r, c):
return r == 0 or r == R - 1 or c == 0 or c == C - 1
if is_border(sr, sc):
return 0
visited = [[False] * C for _ in range(R)]
visited[sr][sc] = True
queue = deque()
queue.append((sr, sc, 0))
while queue:
r, c, t = queue.popleft()
for dr, dc in [(-1,0),(1,0),(0,-1),(0,1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C:
if grid[nr][nc] == 1:
continue
nt = t + 1
if nt >= fire_time[nr][nc]:
continue
if visited[nr][nc]:
continue
visited[nr][nc] = True
if is_border(nr, nc):
return nt
queue.append((nr, nc, nt))
return -1