Rotting Oranges
Medium Graphs AI round
grid is a map of m rows and n columns. Each cell holds 0 for an empty cell, 1 for a fresh orange or 2 for a rotten orange.
Every minute, each rotten orange turns the fresh oranges next to it rotten: the ones directly above, below, left and right of it, not those at a corner. An orange that turns rotten in one minute starts spreading only in the next minute.
Return the number of minutes until no fresh orange is left, or -1 if some fresh orange can never turn rotten. A grid with no fresh orange at the start needs 0 minutes.
Example 1
The rot starts in the top left corner and turns one orange a minute along the top row and down: minute 1, minute 2, minute 3. Minute 4 turns two, one to the right and one below; minutes 5 and 6 carry it left along the bottom row, so the last orange, in the bottom left corner, turns in minute 6.
Example 2
Example 3
Constraints
1 ≤ m, n ≤ 1000m · n ≤ 10⁵- Every row of
gridhasncells grid[i][j]is0,1or2
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
Watch the explanation
More Graphs
- Number of IslandsAI round · Medium
- Word LadderAI round · Hard
- Graph Valid TreeMedium
- Walls and GatesMedium
- Number of Connected Components in an Undirected GraphMedium