Keep a heat count per tree, fed only by last minute's new fires
3. Find the waste. A tree's count of burning neighbors changes only when a neighbor catches. So keep two things:
fresh, the cells that caught last minute. At the start that's every fire.heat, a dict from a tree to how many of its neighbors are burning so far.
Each minute, every fresh cell adds one heat to each unburnt tree beside it, and a tree whose heat reaches k catches. Collect the catches first and apply them after all the reads, so a tree that catches this minute heats nobody until the next one.
def minutes_to_burn_k(grid, k=1):
state = [list(row) for row in grid]
fresh = [(r, c) for r, row in enumerate(grid) for c, ch in enumerate(row) if ch == "F"]
# tree -> burning neighbors so far
heat = {}
minutes = 0
while fresh:
catching = []
# only last minute's new fires
for r, c in fresh:
for nr, nc in open_neighbors(grid, r, c):
if state[nr][nc] == ".":
heat[nr, nc] = heat.get((nr, nc), 0) + 1
# == so each tree is added once
if heat[nr, nc] == k:
catching.append((nr, nc))
# all at once, after the reads
for r, c in catching:
state[r][c] = "F"
if catching:
minutes += 1
fresh = catching
return -1 if any("." in row for row in state) else minutes
fresh is the level-by-level loop again, with the catches standing in for the next level. Here is each pass on the k = 2 forest, ["F.F", "...", "F.."], after the fresh fires have added their heat:
pass 1 pass 2 pass 3 pass 4 pass 5 * is fresh, caught the minute before. F is an older fire. A digit is an unburnt tree's heat. Catches: (0,1) and (1,0), then (1,1), then (2,1) and (1,2), then (2,2), then nothing.
A tree catches on the pass its heat reaches 2. Heat stays between passes: (1,2) gets 1 on pass 1 and its second on pass 3. On pass 5, (2,2) is the only fresh cell, it has no unburnt neighbor, nothing catches, and the loop ends. Four passes caught something, every tree is burning, so the answer is 4, the same as the rescan.
In the editor is minutes_to_burn_k with one bug, and it says -1 for the k = 2 forest. Find the bug and fix it.