Skills101
← All coding problems

Rotting Oranges (Multi-source BFS)

mediumGraphs+20 XPTime limit 2s

Each cell of the grid is empty (0), a fresh orange (1) or a rotten orange (2). Every minute, every fresh orange next to (up/down/left/right) a rotten one becomes rotten. How many minutes until no fresh orange is left? Print -1 if that never happens.

Input:

  • line 1: r c
  • next r lines: c values each

Output: the number of minutes, or -1.

Constraints: 1 ≤ r, c ≤ 300.

Think about it: put all rotten oranges in the queue at time 0 (multi-source BFS) and spread level by level — each level is one minute. If no orange is fresh at the start, the answer is 0.

Sample input 1

3 3
2 1 1
1 1 0
0 1 1

Sample output 1

4

Sample input 2

3 3
2 1 1
0 1 1
1 0 1

Sample output 2

-1

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.