☰ All problems

Rotting Oranges

MediumBFSMatrixGraph

A fruit wholesaler packs oranges into a tray of m × n slots, described by grid, where each slot holds one of three values:

  • 0: the slot is empty,
  • 1: the slot holds a fresh orange,
  • 2: the slot holds a rotten orange.

Rot spreads once a minute: at the end of each minute, every fresh orange directly above, below, left or right of a rotten orange turns rotten too. Empty slots stop the spread.

Return how many minutes pass before no fresh orange is left in the tray. If some fresh orange can never be reached by the rot, return -1. If the tray starts with no fresh oranges, return 0.

Example 1
Input: grid = [[1,1,1],[0,0,1],[2,1,1]]
Output: 6

Explanation: The rot creeps along the bottom row, up the right-hand column and back along the top row, one slot per minute.

Example 2
Input: grid = [[2,0,1],[0,0,1]]
Output: -1

Explanation: Empty slots wall off the two fresh oranges on the right.

Example 3
Input: grid = [[2,2],[0,2]]
Output: 0

Explanation: There are no fresh oranges, so no time needs to pass.

Constraints

  • The tray has between 1 and 10 rows and between 1 and 10 columns.
  • Every slot holds 0, 1 or 2.
💡 Hint 1

All rotten oranges spread at the same time, so treat them all as starting points of one search.

💡 Hint 2

A multi-source BFS processes the grid one "minute" (one BFS level) at a time.

💡 Hint 3

Count the fresh oranges first. Each time one rots, decrement the count; if it is not zero when the BFS ends, return -1.

/**
 * @param {number[][]} grid
 * @return {number}
 */
function orangesRotting(grid) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc