cheetcode

85. Rotting OrangesMedium

Compute how long it takes rot to spread through adjacent fresh oranges.

Each minute, any fresh orange adjacent to a rotten orange becomes rotten.

Return the minimum time needed until no fresh orange remains, or -1 if impossible.

Model the relationships explicitly, then choose BFS, DFS, or union find based on the question. Track visited state so cycles do not create repeated work.

Examples

Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1

Constraints

  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2.