Rotting Oranges

Medium#994grid

A grid holds empty cells, fresh oranges and rotten ones. Every minute each rotten orange spoils the fresh oranges right above, below, left and right of it. Find how many minutes pass until no fresh orange is left, or -1 if some never rot. Our example: RFF. / F.FF / FF.R (R rotten, F fresh, . empty) — the answer is 3.

input
grid: an m × n grid, each cell 0 empty, 1 a fresh orange or 2 a rotten one.
returns
How many minutes pass until no fresh orange is left, or -1 if some never rot. Every minute each rotten orange spoils the fresh ones right above, below, left and right of it.
constraints
  • m = grid.length, n = grid[i].length, 1 ≤ m, n ≤ 10
  • grid[i][j] is 0, 1 or 2
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} grid
 * @return {number}
 */
function orangesRotting(grid) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more breadth-first search (bfs) problems

Pattern “Breadth-first search (BFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.