Rotting Oranges

Given a grid containing fresh oranges, rotten oranges, and empty cells, return the minimum number of minutes needed until no fresh orange remains. Each minute, a rotten orange infects its four-directional neighbors. Pattern focus: BFS. Run a multi-source BFS from all rotten oranges simultaneously.

Input Format

grid = 2D integer matrix

Output Format

minimum minutes to rot all oranges

Constraints

  • 1 <= rows * cols <= 10^5
  • Each cell is 0, 1, or 2.

Examples

Example 1:

Input:

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

Output:

4

Explanation:

All fresh oranges rot after 4 minutes.

Example 2:

Input:

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

Output:

-1

Explanation:

Some fresh oranges can never be reached.

Example 3:

Input:

grid = [[0,2]]

Output:

0

Explanation:

There are no fresh oranges to rot.

Loading...
Rotting Oranges - Graph Traversal DSA Problem