Rotting Oranges

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.
    
    Input Format:
    The first line of input contains two single space-separated integers 'N' and 'M' representing the number of rows and columns of the grid respectively.
    
    The next 'N' lines contain 'M' single space-separated integers each representing the rows of the grid.
    
    Output Format:
    The only line of output contains a single integer i.e. The minimum time after which no cell has a fresh orange. 
    
    If it's impossible to rot all oranges, print -1.
    
    Note:
    You are not required to print the expected output, it has already been taken care of. Just implement the function.
    
    Constraints:
    1 <= N <= 500
    1 <= M <= 500
    0 <= grid[i][j] <= 2
    
    Time Limit: 1 sec
    
    CodingNinjas
    author
    2y
    Naïve Solution

    The idea is very simple and naive. We will process the rotten oranges second by second. Each second, we rot all the fresh oranges that are adjacent to the already rotten oranges. The tim...read more

    CodingNinjas
    author
    2y
    Breadth-First-Solution

    We can use Breadth-First-Search which is similar to the level order traversal of a Binary Tree, to solve this problem.

    We will be using a Queue data structure and inserting cells...read more

    Help your peers!
    Add answer anonymously...
    Icertis Associate Software Engineer Interview Questions
    Stay ahead in your career. Get AmbitionBox app
    qr-code
    Helping over 1 Crore job seekers every month in choosing their right fit company
    65 L+

    Reviews

    4 L+

    Interviews

    4 Cr+

    Salaries

    1 Cr+

    Users/Month

    Contribute to help millions
    Get AmbitionBox app

    Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

    Follow us
    • Youtube
    • Instagram
    • LinkedIn
    • Facebook
    • Twitter