Rotting Oranges (Multi-source BFS) in Java: Explanation & Practice

Minimum time for all oranges to rot

Problem summary

In a grid, 0=empty, 1=fresh orange, 2=rotten. Every minute, fresh oranges adjacent to rotten ones become rotten. Return minimum minutes until no fresh orange remains.

Starter code

public class Main {
    public static void main(String[] args) {
        int[][] grid = {
            {2,1,1},
            {1,1,0},
            {0,1,1}
        };
        
        // Multi-source BFS: start from ALL rotten oranges
        // Each BFS level = 1 minute
        // Print: Minutes: 4
    }
}

Expected output and test cases

  • 4 minutes to rot all
    Minutes: 4
  • Isolated fresh orange
    Minutes: -1
  • No fresh oranges
    Minutes: 0

Hints

  1. Add ALL initial rotten oranges to queue
  2. BFS level by level, each level = 1 minute
  3. Count fresh oranges initially
  4. Decrement count as oranges rot; if count > 0 at end, return -1

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler