Example 1
- Input
- grid = [[2,1,1],[1,1,0],[0,1,1]]
- Output
- 4
Minute 1 rots (0,1) and (1,0), minute 2 rots (0,2) and (1,1), minute 3 rots (2,1), and minute 4 rots (2,2).
Each minute, every fresh orange next to a rotten one rots as well. Given the starting grid, return how many minutes pass until no fresh orange remains, or -1 when an isolated fresh orange can never rot.
You are given an m x n grid where each cell holds 0 for an empty cell, 1 for a fresh orange, or 2 for a rotten orange. Every minute, each fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return the minimum number of minutes that must pass until no cell holds a fresh orange. If some fresh orange can never rot, return -1.
m == grid.lengthn == grid[i].length1 <= m, n <= 10grid[i][j] is 0, 1, or 2.Minute 1 rots (0,1) and (1,0), minute 2 rots (0,2) and (1,1), minute 3 rots (2,1), and minute 4 rots (2,2).
The fresh orange at (2,0) is cut off by empty cells, so rot never reaches it.
No fresh orange exists at the start, so zero minutes pass.
Both endpoint sources spread together. At minute 1 positions 1 and 3 rot; at minute 2 both reach the middle, which is counted only once. Starting from just one source would incorrectly take three minutes to reach all originally fresh cells.
Treat nonempty cells as graph vertices connected by shared sides. A fresh orange rots after the shortest number of side-to-side steps from any initially rotten orange, because all sources spread together once per minute. Empty cells block paths. Example 1 needs four steps to reach (2,2), the last fresh cell. Simulating whole minutes works; a queue of only newly rotten cells avoids rescanning inactive cells. A fresh cell with no path from any source makes the answer -1.
Reveal Minute By Minute Rescan: intuition, complexity, and code
-1 if any remain when the queue empties.[[0,2]], so the answer is 0 without any spreading.-1.-1 even though rot spreads elsewhere.When many sources spread outward in lockstep, enqueue them all first and read the answer off the breadth-first levels.