AlgoMaster Logo

Rotting Oranges

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. BFS (Breadth-First Search) Simulation

Intuition:

The problem is essentially about finding the shortest time it takes for all fresh oranges to become rotten, akin to a multi-source shortest path problem. The oranges that are initially rotten act as multiple starting points and rot adjacent fresh oranges in the four cardinal directions. We can utilize a breadth-first search (BFS) to simulate the process in levels, where each level represents one unit of time.

Steps:

  1. Initialize the Queue and Variables:
    • Use a queue to implement BFS, starting with all initially rotten oranges.
    • Count the number of fresh oranges.
    • A time counter (minutes) to track the time it takes to rot all oranges.
  2. BFS Process:
    • At each BFS level (each minute), process all the oranges in the queue (these are the oranges that rot in the current minute).
    • For each rotten orange, attempt to rot all adjacent fresh oranges.
    • If a fresh orange becomes rotten, decrement the fresh orange count and enqueue it.
  3. Check Results:
    • If at the end of BFS, there are any remaining fresh oranges, it is impossible to rot all oranges, and we return -1.
    • Otherwise, return the time counter which now reflects the total minutes taken.
  4. Edge Cases:
    • If there are no fresh oranges to begin with, return 0 since no time is required.
    • All oranges being rotten initially would also require 0 minutes.

Code: