Maintained by Vikas Dulgunde, software engineer
You are given a grid of size m by n. Each cell holds one of three values: 0 for an empty cell, 1 for a fresh orange, and 2 for a rotten orange.
Rot spreads in steps. During each minute, every fresh orange that shares an edge with a rotten orange (up, down, left, or right) turns rotten as well. Diagonal neighbours do not count.
Return the smallest number of minutes that must pass before no fresh orange is left. If at least one fresh orange is walled off from all rot and can never turn, return -1 instead.
If the grid starts with no fresh oranges at all, the answer is 0, because there is nothing left to rot.
The single rotten orange at the top-left spreads outward one ring per minute. After minute 1 its two neighbours rot, and the wave continues until the last fresh orange in the bottom-right rots at minute 4.
The fresh orange at the bottom-left corner has only empty cells and the grid edge around it, so no rot ever reaches it. Since a fresh orange survives forever, the answer is -1.
There are no fresh oranges to begin with, so zero minutes are needed.
The rotten orange in the bottom-right rots its two edge neighbours at minute 1, then the remaining top-left orange rots at minute 2.
Visible test cases
All rotten oranges spread at the same time, so this is not a single starting point. Think about advancing every rot source together, one ring at a time.
A breadth-first search that begins from every rotten cell at once visits cells in exactly the order they rot. The depth of that search is the number of minutes.
Count the fresh oranges up front. After the search finishes, if any fresh orange remains uncounted as rotted, the spread could not reach it, so return -1.
Simulate one minute at a time by scanning the whole grid, marking every fresh orange adjacent to a rotten one, then applying all of those changes together before the next minute.
Seed a queue with every rotten orange and process the queue level by level. Each level is one minute of spread, so the number of levels processed is the answer.