Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Rotting Oranges

Moderate
0/80
Average time to solve is 20m
profile
Contributed by
122 upvotes
Asked in companies
SamsungMicrosoftAmazon

Problem statement

You have been given a grid containing some oranges. Each cell of this grid has one of the three integers values:

  • Value 0 - representing an empty cell.
  • Value 1 - representing a fresh orange.
  • Value 2 - representing a rotten orange.
  • Every second, any fresh orange that is adjacent(4-directionally) to a rotten orange becomes rotten.

    Your task is to find out the minimum time after which no cell has a fresh orange. If it's impossible to rot all the fresh oranges then print -1.

    Note:
    1. The grid has 0-based indexing.
    2. A rotten orange can affect the adjacent oranges 4 directionally i.e. Up, Down, Left, Right.
    
    Detailed explanation ( Input/output format, Notes, Images )
    Constraints:
    1 <= N <= 500
    1 <= M <= 500
    0 <= grid[i][j] <= 2
    
    Time Limit: 1 sec
    
    Sample Input 1:
    3 3
    2 1 1
    1 1 0
    0 1 1 
    
    Sample Output 1:
    4
    
    Explanation of Sample Input 1:
    Minimum 4 seconds are required to rot all the oranges in the grid as shown below.
    

    alt text

    Sample Input 2:
    3 3
    2 1 0
    0 1 1
    1 0 1
    
    Sample Output 2:
    -1
    
    Explanation of Sample Input 2:
    The bottom left corner fresh orange (row 2, column 0) has no adjacent oranges. Hence, it's impossible to rot it.
    
    Full screen
    Console