InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Rotting Oranges

medium Original ↗ 00:00

Problem

You’re given an m x n grid where each cell is:

  • 0 — empty,
  • 1 — a fresh orange,
  • 2 — a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent (up/down/left/right) to a rotten orange becomes rotten. Return the minimum number of minutes that must pass until no fresh orange remains. If some fresh orange can never rot, return -1.

Examples

  • grid = [[2,1,1],[1,1,0],[0,1,1]]4 — rot spreads outward from the top-left; the last fresh orange (bottom-right) rots at minute 4.
  • grid = [[2,1,1],[0,1,1],[1,0,1]]-1 — the fresh orange at the bottom-left corner is isolated by empty cells and never rots.
  • grid = [[0,2]]0 — there are no fresh oranges to begin with, so zero minutes pass.

Constraints

  • 1 <= m, n <= 10
  • Each cell is 0, 1, or 2.
  • Rot spreads to all four neighbors simultaneously each minute.

Think about it first

Hint 1 All rotten oranges spread at the same time each minute. Everything at distance 1 rots first, then everything at distance 2, and so on. That is what a breadth-first traversal produces.
Hint 2 Use breadth-first search seeded with every rotten orange at once (multi-source BFS). Each BFS level is one minute. The number of levels until the queue drains is the elapsed time.
Hint 3 Count the fresh oranges up front. Run the level-by-level BFS, decrementing the fresh count as each orange rots. If any fresh oranges remain at the end, they were unreachable, so return `-1`; otherwise return the number of minutes elapsed.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug