TRT
Sign in
mediumAdvancedLeetCode#multi-source BFS#grid BFS

Rotting oranges

Find how many minutes it takes rot to spread from every rotten orange to all fresh ones, with a multi-source BFS.

The Runtime Theory Team1 min read
Taught inBreadth-first searchPro — members onlyBreadth-first search explores a graph in rings of increasing distance from the start, using a queue and a visited set. In an unweighted graph, the first time it reaches a vertex is along a shortest path.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ingrid = [[2, 1, 1], [1, 1, 0], [0, 1, 1]]

out4

ingrid = [[2, 1, 1], [0, 1, 1], [1, 0, 1]]

out-1

ingrid = [[0, 2]]

out0

In a grid, 0 is empty, 1 is a fresh orange and 2 a rotten one. Every minute, fresh oranges next to rotten ones rot. Return the minutes until no fresh orange remains, or -1 if that never happens.

Before you code

The rot spreads from all rotten oranges at once. Starting all of them in the queue together gives every fresh orange its distance to the nearest rotten one.

Hints

  1. Enqueue every rotten orange with time 0 and count the fresh ones.
  2. BFS level by level; each level is one minute. Rot fresh neighbors as you enqueue them, decrementing the fresh count.
  3. If the fresh count is not 0 at the end, return -1.

Production & complexity notes

When solving Rotting oranges on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Breadth-first search to reinforce the underlying pattern.

What it practices

BFS from several sources at once, from Breadth-first search.

Not started

Sign in to save your learning progress.

Sign in to save