Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

143. Rotting Oranges

MediumDay 42 of 60Graphs

In an m x n grid, each cell is 0 (empty), 1 (fresh orange) or 2 (rotten orange). Every minute, each fresh orange that is next to a rotten one (up, down, left or right) becomes rotten. Return the minimum number of minutes until no fresh orange is left, or -1 if some fresh orange can never rot.

Example 1
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
The rot spreads one layer per minute and reaches the bottom right orange after 4 minutes.
Example 2
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
The orange at the bottom left is cut off and never rots.
Constraints
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1 or 2
Hints
Frequently asked at: Amazon, Microsoft, Google, Flipkart
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min