#2258
Escape the Spreading Fire
HardArrayBinary SearchBreadth-First SearchMatrixBreadth-First Search (BFS)Binary Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses a multi-source BFS to calculate the time it takes for the fire to reach each cell and then uses binary search to find the maximum delay time the player can wait before moving.
⚙️
Algorithm
3 steps- 1Step 1: Perform a multi-source BFS to calculate the earliest time the fire reaches each cell.
- 2Step 2: Use binary search on the delay time to find the maximum time the player can wait before moving.
- 3Step 3: For each mid value in the binary search, check if the player can reach the safehouse before the fire using BFS.
solution.py49 lines
1# Full working Python code
2from collections import deque
3
4def escapeFire(grid):
5 m, n = len(grid), len(grid[0])
6 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
7
8 def bfs_fire():
9 fire_time = [[float('inf')] * n for _ in range(m)]
10 queue = deque()
11 for i in range(m):
12 for j in range(n):
13 if grid[i][j] == 1:
14 queue.append((i, j))
15 fire_time[i][j] = 0
16 while queue:
17 x, y = queue.popleft()
18 for dx, dy in directions:
19 nx, ny = x + dx, y + dy
20 if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == 0:
21 fire_time[nx][ny] = fire_time[x][y] + 1
22 queue.append((nx, ny))
23 return fire_time
24
25 fire_time = bfs_fire()
26
27 def can_escape(delay):
28 queue = deque([(0, 0, delay)])
29 visited = set((0, 0))
30 while queue:
31 x, y, time = queue.popleft()
32 if (x, y) == (m - 1, n - 1):
33 return True
34 for dx, dy in directions:
35 nx, ny = x + dx, y + dy
36 if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in visited and grid[nx][ny] == 0:
37 if time + 1 < fire_time[nx][ny]:
38 visited.add((nx, ny))
39 queue.append((nx, ny, time + 1))
40 return False
41
42 left, right = 0, 10**9
43 while left < right:
44 mid = (left + right + 1) // 2
45 if can_escape(mid):
46 left = mid
47 else:
48 right = mid - 1
49 return left if can_escape(left) else -1ℹ
Complexity note: The BFS for fire spread is O(n), and the binary search runs in O(log n) for the maximum delay, leading to an overall complexity of O(n log n).
- 1Understanding fire spread is crucial for determining safe paths.
- 2Binary search helps efficiently find the maximum delay time.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.