22/32
Part 6 of 7 · The worked exampleLearn and do

A worked example: a fire that needs k neighbors

The problem: a forest of trees ., rocks # and fires F. A tree catches on a minute when at least k of its neighbors were burning the minute before, and fires never go out. Return the minutes until every tree burns, 0 if none is left to burn at the start, or -1 if some tree never catches. This is how a candidate should take it.

Say the rules back, then start from the rescan that is plainly right

1. Say the rules back. Neighbors share a side. Rocks never burn and never count. Every change in a minute reads the minute before. Then ask the questions the tests will ask:

  • No trees at all: 0.
  • No fire: -1, unless there are no trees.
  • k above 4: no tree has five neighbors, so nothing ever catches.

2. Start with the version that's plainly right. That's minutes_by_rescan: rounds that read the old grid and write a new one. State its cost, O(RC)O(RC) per minute, and offer to make it faster.

In the editor, write quick_answer(grid, k): the answer for those three cases, or None when only a simulation can tell.