Skip to content
BASA DSA

Rotting Oranges

MediumGraphs

A grid contains empty cells 0, fresh oranges 1 and rotten oranges 2. Each minute, rotten oranges simultaneously rot orthogonally adjacent fresh ones. Return minutes until none are fresh, or -1 if impossible.

Example 1

0,02
0,11
0,21
1,00
1,11
1,21
0 = empty; 1 = fresh orange; 2 = rotten orange. Rot spreads to horizontal and vertical neighbors.
Input
grid = [[2,1,1],[0,1,1]]
Output
3

Explanation

Rotting reaches (0,1), then (0,2)/(1,1), then (1,2), requiring three minutes.

Example 2

0,02
0,10
0,21
0 = empty; 1 = fresh orange; 2 = rotten orange. Rot spreads to horizontal and vertical neighbors.
Input
grid = [[2,0,1]]
Output
-1

Explanation

An empty cell separates the rotten and fresh orange, so the fresh one is unreachable.

Example 3

0,00
0,12
0 = empty; 1 = fresh orange; 2 = rotten orange. Rot spreads to horizontal and vertical neighbors.
Input
grid = [[0,2]]
Output
0

Explanation

No fresh oranges exist initially, requiring zero minutes.

Constraints

  • 1 <= rows, columns <= 10

Function contractorangesRottingArguments: json
Loading draft…
SolutionRuns on your device
Loading draft…