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
- Add ALL initial rotten oranges to queue
- BFS level by level, each level = 1 minute
- Count fresh oranges initially
- Decrement count as oranges rot; if count > 0 at end, return -1
Related Data Structures & Algorithms exercises
- Practice Course Schedule (Cycle Detection) in Java
- Practice Word Ladder (Shortest Path) in Java
- Practice Jump Game in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler