Rotting Oranges

Medium · Graphs · Array · BFS · Matrix

Problem

A grid holds 0 (empty), 1 (fresh orange) or 2 (rotten orange). Each minute, every fresh orange adjacent to a rotten one (up, down, left, right) becomes rotten.

Return the minutes until no fresh orange remains, or -1 if some can never rot.

Examples

Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4

Rot spreads outward from the single source.

Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1

The bottom-left orange is unreachable.

Input: grid = [[0,2]]
Output: 0

No fresh oranges to begin with.

Constraints

Approaches

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…