Rotting oranges: minutes until every orange is rotten
Coding problemMedium-HardAsked in: Amazon
A grid of whole numbers describes a box of oranges: 0 is an empty cell, 1 a fresh orange and 2 a rotten orange. Every minute, each fresh orange directly next to a rotten one (up, down, left or right) becomes rotten.
Return the number of minutes until no fresh orange is left. If some fresh orange can never rot, return -1. If there are no fresh oranges at the start, return 0.
Examples
Example 1
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
The orange in the bottom left corner has no neighbour that can rot it.
Example 3
Input: grid = [[0,2]]
Output: 0
Constraints
- The grid has between 1 and 300 rows and between 1 and 300 columns
- Every cell is 0, 1 or 2
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.