Start from every source at once
Put every source on the queue at step 0, and each count is the fewest steps to the nearest one
Spread questions start from many places at once: several fires, every rotten orange, all the infected cells on day 0. It takes one change to steps_from:
def steps_to_nearest(grid, sources):
steps = {cell: 0 for cell in sources}
queue = deque(sources)
while queue:
r, c = queue.popleft()
for cell in open_neighbors(grid, r, c):
if cell not in steps:
steps[cell] = steps[r, c] + 1
queue.append(cell)
return steps
Every source goes on the queue at step 0, before the first pop. Here are two fires at the ends of a row:
minute Minute 0's queue holds both fires. They spread in the same minutes and meet at (0,3), the last cell queued.
Both fires are level 0, so they spread in the same minutes and meet in the middle at minute 3.
A tree catches when the nearest fire reaches it. So you want each cell's distance to its nearest source, and the answer is the largest of those. Picture one extra cell joined to every source by an edge. BFS from that cell would pop it, queue all the sources, and carry on exactly like this. So everything above about BFS holds, and each count is the fewest steps from the nearest source.
Here it is on a forest with two fires and a wall of rock:
Fires at (0,0) and (2,5) in ["F.....", "..#...", "..#..F", "......"]. What count does (0,4) get?