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.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- 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.
Use this to learn the idea, then write your own version.
1class Solution:2 def maximumMinutes(self, grid: list[list[int]]) -> int:3 DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))4 MAX = len(grid) * len(grid[0])5 fireGrid = [[-1] * len(grid[0]) for _ in range(len(grid[0]))]6 self._buildFireGrid(grid, fireGrid, DIRS)7 8 ans = -19 l = 010 r = MAX11 12 while l <= r:13 m = (l + r) 214 if self._canStayFor(grid, fireGrid, m, DIRS):15 ans = m16 l = m + 117 else:18 r = m - 119 20 return 1e9 if ans == MAX else ans21 22 def _buildFireGrid(23 self,24 grid: list[list[int]],25 fireMinute: list[list[int]],26 DIRS: list[int],27 ) -> None:28 minuteFromFire = 029 q = collections.deque()30 31 for i in range(len(grid)):32 for j in range(len(grid[0])):33 if grid[i][j] == 1: 34 q.append((i, j))35 fireMinute[i][j] = 036 37 while q:38 minuteFromFire += 139 for _ in range(len(q)):40 i, j = q.popleft()41 for dx, dy in DIRS:42 x = i + dx43 y = j + dy44 if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]):45 continue46 if grid[x][y] == 2: 47 continue48 if fireMinute[x][y] != -1:49 continue50 fireMinute[x][y] = minuteFromFire51 q.append((x, y))52 53 def _canStayFor(54 self,55 grid: list[list[int]],56 fireMinute: list[list[int]],57 minute: int, DIRS: list[int],58 ) -> bool:59 q = collections.deque([(0, 0)]) 60 seen = {(0, 0)}61 62 while q:63 minute += 164 for _ in range(len(q)):65 i, j = q.popleft()66 for dx, dy in DIRS:67 x = i + dx68 y = j + dy69 if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]):70 continue71 if grid[x][y] == 2: 72 continue73 if x == len(grid) - 1 and y == len(grid[0]) - 1:74 if fireMinute[x][y] != -1 and fireMinute[x][y] < minute:75 continue76 return True77 if fireMinute[x][y] != -1 and fireMinute[x][y] <= minute:78 continue79 if seen[x][y]:80 continue81 q.append((x, y))82 seen.add((x, y))83 84 return False85