☰ All problems

63. Rotting Oranges

MediumBFSMatrixGraph

A crate is modelled as an m × n grid where each cell holds:

  • 0: an empty spot,
  • 1: a fresh orange,
  • 2: a rotten orange.

Every minute, each fresh orange that is horizontally or vertically next to a rotten orange becomes rotten itself.

Return the number of minutes that pass until no fresh orange is left. If some fresh orange can never rot, return -1. If there are no fresh oranges to begin with, the answer is 0.

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

Explanation: The rot spreads right and down in minute 1, reaches the centre in minute 2, then the bottom middle in minute 3 and the bottom-right orange in minute 4.

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

Explanation: The empty cell separates the fresh orange from the rotten one.

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

Constraints

  • 1 <= m, n <= 10
  • grid[i][j] is 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