Signal Propagation Time to All Destinations
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests understanding of multi-source BFS to compute the longest shortest path from any source to all required destinations on a grid with obstacles.
You're working with a rectangular grid that models signal propagation. The grid has m rows and n columns, where each cell contains one of four values:
'S': A transmitter that begins broadcasting at time0.'T': A destination that must receive the broadcast.'B': A barrier that completely blocks signal transmission.'.': Open space through which signals freely travel.
All transmitters begin broadcasting simultaneously at time 0. During each time unit, signals expand from their current positions to all four adjacent cells (up, down, left, right), as long as those cells are within the grid boundaries and are not barriers. Signals pass through both open spaces and destinations without obstruction.
Your task is to determine the minimum time required for signals to reach all destination cells. If the grid contains no destinations, return 0. If any destination is unreachable from all transmitters, return -1.
Constraints
m == len(grid)n == len(grid[i])1 <= m, n <= 500- Each
grid[r][c]is one of'S','T','B', or'.'
Examples
Example 1
Input: signal_propagation_time([['S', '.', '.', 'B'], ['.', 'B', '.', 'T'], ['.', 'T', '.', '.']])
Output: 4
Example 2
Input: signal_propagation_time([['S', 'B', 'T'], ['B', 'B', '.'], ['.', '.', 'T']])
Output: -1
Example 3
Input: signal_propagation_time([['S', '.'], ['.', '.']])
Output: 0
Hints
Hint 1
Think about starting from all transmitters at once rather than running separate searches from each one.
Hint 2
The answer is determined by whichever destination takes the longest to reach, not the first one.
Hint 3
Mark cells as visited when you add them to the queue, not when you process them, to avoid processing the same cell multiple times.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires finding the shortest distance from any transmitter to each destination, then taking the maximum across all destinations. The key insight is to use multi-source breadth-first search rather than running separate searches from each transmitter.
Start by placing all transmitters in a queue with time 0 and marking them as visited. Then perform BFS layer by layer:
- Scan the grid to identify all transmitters and count destinations
- If no destinations exist, immediately return
0 - Initialize all transmitters in the queue at time
0and mark them visited - Process cells level by level, expanding to valid neighbors (in-bounds, not barriers, not yet visited)
- When a destination is dequeued, increment the count of reached destinations and track the maximum time
- After the queue empties, return the maximum time if all destinations were reached, otherwise
-1
Why It Works
Multi-source BFS computes the shortest path distance from each cell to its nearest transmitter in a single pass. Conceptually, it's equivalent to adding a virtual super-transmitter connected to all real transmitters with zero-cost edges, then running standard BFS.
The queue processes cells in non-decreasing time order, so the first time any cell is discovered gives its true shortest arrival time. Marking cells visited when enqueued (not dequeued) ensures each cell is processed exactly once and retains its earliest arrival time.
Since we need all destinations covered, the answer is the maximum time among all destinations—the "slowest" destination determines when the task completes. If any destination is never visited, no path exists from any transmitter to that destination through non-barrier cells.
Complexity
Time: O(m · n) — Each cell is enqueued at most once, and each dequeue examines 4 neighbors. With up to 500 × 500 = 250,000 cells, this is efficient.
Space: O(m · n) — The visited matrix and queue both scale with grid size. In the worst case, the queue may hold an entire wavefront or all transmitters.
Solution
from collections import deque
from typing import List
def signal_propagation_time(grid: List[List[str]]) -> int:
m = len(grid)
n = len(grid[0])
queue = deque()
destination_count = 0
for r in range(m):
for c in range(n):
if grid[r][c] == 'S':
queue.append((r, c, 0))
elif grid[r][c] == 'T':
destination_count += 1
if destination_count == 0:
return 0
visited = [[False] * n for _ in range(m)]
for r, c, _ in queue:
visited[r][c] = True
destinations_reached = 0
max_time = 0
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue:
r, c, time = queue.popleft()
if grid[r][c] == 'T':
destinations_reached += 1
max_time = max(max_time, time)
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n:
if not visited[nr][nc] and grid[nr][nc] != 'B':
visited[nr][nc] = True
queue.append((nr, nc, time + 1))
return max_time if destinations_reached == destination_count else -1