Forest Fire

Medium

This is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.

Question

You're given a grid that stands for a patch of forest. Each cell is 0, 1, or 2. A 0 is bare ground, a 1 is a healthy tree, and a 2 is a tree that's already on fire.

Every minute, the fire spreads from each burning tree to the healthy trees right above, below, left, and right of it. Return how many minutes it takes until no healthy trees are left. If some healthy tree can never catch fire, return -1.

Input: grid = [[2, 1, 1], [1, 1, 0], [0, 1, 1]]

Output: 4

The fire spreads out one step per minute from the burning tree in the top-left corner. Bare cells never catch fire. The last healthy tree catches fire on minute 4.

Input: grid = [[2, 1, 1], [0, 1, 1], [1, 0, 1]]

Output: -1

The tree in the bottom-left corner only touches bare ground. It can never catch fire, no matter how long we wait.

Input: grid = [[2, 2], [2, 2]]

Output: 0

Every tree is already burning. So 0 minutes pass.

You might also hear this problem called “Rotting Oranges.”

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

Every healthy tree in this grid eventually catches fire. How many minutes does it take? grid = [[0, 1, 1], [1, 1, 2], [1, 1, 0]]
2
3
4
-1

Remember to understand the problem and plan your approach before you start coding.