Rotten Oranges

Graphs Traversal Problems Medium
  • This problem is an instance of the Breadth-First Search (BFS) algorithm and simulates a typical spread mechanism like virus propagation, pollution spread, etc
  • A practical software application of this concept can be found in computer graphics used for animation and game development
  • Here, this BFS algorithm can be used for "flood fill" operations, where you "fill" or change the color of a particular area on the screen (like converting all the fresh oranges to rotten ones in our problem)
  • Additionally, the BFS algorithm is also used in networking software to traverse nodes or routers, and in social media algorithms to understand and predict how information or trends spread across a network

Given an n x m grid, where each cell has the following values : 


2 - represents a rotten orange

1 - represents a Fresh orange

0 - represents an Empty Cell

Every minute, if a fresh orange is adjacent to a rotten orange in 4-direction ( upward, downwards, right, and left ) it becomes rotten. 


Return the minimum number of minutes required such that none of the cells has a Fresh Orange. If it's not possible, return -1.

Examples:

Input: grid = [ [2, 1, 1] , [0, 1, 1] , [1, 0, 1] ]

Output: -1

Explanation: Orange at (3,0) cannot be rotten.


Input: grid = [ [2,1,1] , [1,1,0] , [0,1,1] ] 

Output: 4

Explanation:

Input: grid = [[0,1,2],[0,1,2],[2,1,1]]

Constraints

  •   1 <= n, m <= 500
  •   grid[i][j] == 0 or 1 or 2

Hints

  • "Since the rot spreads level by level, BFS (Queue-based) is the best approach. Push all initially rotten oranges (2) into the queue as starting points. Process oranges minute by minute, marking newly rotten oranges and tracking time."
  • "Count the total fresh oranges (1s) initially. Track the number of fresh oranges that rot over time. If, after BFS, some fresh oranges remain, return -1 (not all oranges can rot)."

Company Tags

Walmart Robinhood Splunk Roche Johnson & Johnson Chewy Dropbox Lyft Electronic Arts Micron Technology Philips Healthcare Activision Blizzard Docker Unity Technologies Wayfair Ernst & Young IBM Bain & Company Shopify Alibaba Zynga GE Healthcare Rockstar Games Western Digital Medtronic Google Microsoft Amazon Meta Apple Netflix Adobe