Mold on the Bakery Shelf
Medium · Graphs, BFS & DFS · about 20 min
A bakery shelf is a grid of slots. 0 is an empty slot, 1 is a fresh loaf and 2 is a moldy loaf. Every minute, each moldy loaf makes the fresh loaves directly up, down, left and right of it moldy (not diagonally). All moldy loaves spread at the same time.
Return the number of minutes until no fresh loaf is left. Return 0 if there are no fresh loaves at the start, and -1 if some fresh loaf can never become moldy.
- The grid has at least one row and one column.
Example:
minutes_until_all_moldy([[2, 1, 1], [1, 1, 0], [0, 1, 1]]) → 4
Hints
- Put every moldy loaf into the queue at the very start, and count the fresh loaves.
- Handle the queue one level at a time. One level is one minute.
- Only count a minute when that level actually turned at least one fresh loaf. At the end, if any fresh loaf is left, the answer is -1.
Learn the pattern first: the Graphs, BFS & DFS lesson.
More Graphs, BFS & DFS problems
- Repaint Connected Tiles (Easy)
- Largest Crop Field (Easy)
- Can the Van Get There? (Easy)
- Steps to the Nearest Fire Exit (Medium)
- Rain That Reaches Both Coasts (Medium)
- Fill the Landlocked Ponds (Medium)
- Copy a Network With New Labels (Medium)
- Shortest Clear Path for a Rover (Hard)
- Code Word Relay (Hard)