Problem 504316 · medium · Level 05 Advanced Algorithms & Graphs

Mould in the Fruit Crate

bfs · multi-source bfs · grid

When several things spread at the same speed from several starting points, put all of them in the BFS queue before you start. Every layer of the search is then one unit of time, no matter how many sources there are.

A crate of oranges is packed as an m x n grid: 0 is an empty slot, 1 a fresh orange and 2 a mouldy one. Each hour, mould spreads from every mouldy orange to each fresh orange directly above, below, left or right of it. Write oranges_rotting(grid) that returns how many hours pass until no fresh orange is left, or -1 if some fresh orange can never be reached.

Examples

Input:  grid = [[2,1,1,1,2],[0,1,0,1,0],[1,1,0,1,1]]
Output: 4
Explanation: both mouldy oranges spread at the same time; the two bottom corners go mouldy last, in hour 4

Input:  grid = [[2,1,0],[1,1,0],[0,0,1]]
Output: -1
Explanation: the orange in the bottom-right corner is never reached

Input:  grid = [[2,0,2]]
Output: 0
Explanation: there are no fresh oranges to begin with

Constraints

  • 1 <= m, n <= 10
  • Target: O(m * n) time

Goals

  • Seed a BFS queue with several sources at once so every source spreads simultaneously
  • Process BFS level by level to count elapsed time
  • Detect unreachable cells after the search finishes
Starting Python…