Facebook Pixel

Rotting Oranges

JavaScript
medium
30 mins

Write a function that determines the minimum number of minutes required for all fresh oranges in a grid to become rotten. Every minute, any fresh orange that is 4-directionally adjacent (up, down, left, right) to a rotten orange also becomes rotten. If it is impossible to rot all fresh oranges, return -1.

Input: A 2D array grid representing the grid of oranges. Each cell in the grid can be:

0 → an empty cell

1 → a fresh orange

2 → a rotten orange

Output: Return the minimum number of minutes it takes for all fresh oranges to become rotten. If it’s not possible, return -1.

Constraints & Edge Cases

The grid can be empty.

  • There may be no fresh or no rotten oranges at the start.

  • Rotten oranges spread the rot to adjacent fresh oranges in 4 directions: up, down, left, and right.

  • If fresh oranges are blocked by empty cells and can’t be reached, return -1.

  • If there are no fresh oranges initially, return 0.

  • If all oranges are already rotten, return 0.

Companies:

amazon
microsoft
linkedin
namasteDev
pineapple

Solve Similar questions 🔥