Python coding

Minutes until every tree burns

A field is a list of equal-length strings: "F" is a cell on fire, "T" is a tree and "." is bare ground that never burns. Every minute, each burning cell sets fire to the trees directly above, below, left and right of it. Return the number of minutes until every tree is on fire, or -1 if some tree can never burn.

There may be several fires, or none; if the field has no trees (or is empty), the answer is 0.

Besides the tests, one large input (a 50 × 50 forest, 289 fires) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • minutes_to_burn(["FTT","TT.",".TT"]) → 4
  • minutes_to_burn(["F.T","TTT","T.F"]) → 2
  • minutes_to_burn(["FT.","..T"]) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Fire spreads one cell per minute in every direction at once: that is BFS, where a cell's level is the minute it catches fire.

Hint 2

Don't run one BFS per fire. Put every burning cell in the queue at minute 0 and let a single BFS expand them together.

Hint 3

Count the trees up front and decrement as each one ignites. The answer is the minute of the last ignition, or -1 if the count never reaches zero.

Solution and why it works
pythonO(R·C), R × C = field size · O(R·C)
from collections import deque


def minutes_to_burn(field: list[str]) -> int:
    grid = [list(row) for row in field]
    queue, trees = deque(), 0
    for r, row in enumerate(grid):
        for c, cell in enumerate(row):
            if cell == "F":
                queue.append((r, c, 0))          # every fire starts at minute 0
            elif cell == "T":
                trees += 1
    minute = 0
    while queue:
        r, c, minute = queue.popleft()
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == "T":
                grid[nr][nc] = "F"               # mark when queued, not when popped
                trees -= 1
                queue.append((nr, nc, minute + 1))
    return minute if trees == 0 else -1

Seeding the queue with every fire at minute 0 makes BFS expand all of them level by level, so each tree is first reached by its nearest fire, at exactly the minute it ignites. Marking a tree as burning when it is queued keeps the work at O(R·C). Count trees up front: if some remain when the queue empties, they are cut off and the answer is -1. The trap is one BFS per fire, which repeats the whole grid for each source.