Problem solution · Python

Escape the Spreading Fire

Escape the Spreading Fire: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
85 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Escape the Spreading Fire, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 85 lines of Python from the credited upstream file 2258.py.
  • The implementation visibly relies on sequence storage, work queue.
  • No explicit loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeEscape the Spreading Fire · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def maximumMinutes(self, grid: list[list[int]]) -> int:    DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))    MAX = len(grid) * len(grid[0])    fireGrid = [[-1] * len(grid[0]) for _ in range(len(grid[0]))]    self._buildFireGrid(grid, fireGrid, DIRS)     ans = -1    l = 0    r = MAX     while l <= r:      m = (l + r) // 2      if self._canStayFor(grid, fireGrid, m, DIRS):        ans = m        l = m + 1      else:        r = m - 1     return 1e9 if ans == MAX else ans   def _buildFireGrid(      self,      grid: list[list[int]],      fireMinute: list[list[int]],      DIRS: list[int],  ) -> None:    minuteFromFire = 0    q = collections.deque()     for i in range(len(grid)):      for j in range(len(grid[0])):        if grid[i][j] == 1:  # the fire          q.append((i, j))          fireMinute[i][j] = 0     while q:      minuteFromFire += 1      for _ in range(len(q)):        i, j = q.popleft()        for dx, dy in DIRS:          x = i + dx          y = j + dy          if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]):            continue          if grid[x][y] == 2:  # the wall            continue          if fireMinute[x][y] != -1:            continue          fireMinute[x][y] = minuteFromFire          q.append((x, y))   def _canStayFor(      self,      grid: list[list[int]],      fireMinute: list[list[int]],      minute: int, DIRS: list[int],  ) -> bool:    q = collections.deque([(0, 0)])  # the start position    seen = {(0, 0)}     while q:      minute += 1      for _ in range(len(q)):        i, j = q.popleft()        for dx, dy in DIRS:          x = i + dx          y = j + dy          if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]):            continue          if grid[x][y] == 2:  # the wall            continue          if x == len(grid) - 1 and y == len(grid[0]) - 1:            if fireMinute[x][y] != -1 and fireMinute[x][y] < minute:              continue            return True          if fireMinute[x][y] != -1 and fireMinute[x][y] <= minute:            continue          if seen[x][y]:            continue          q.append((x, y))          seen.add((x, y))     return False 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗