AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

Rotting Oranges

The key idea

Every rotten orange spreads at the same time, so model it as a multi-source BFS: seed the queue with all initially rotten oranges at once and expand level by level. Each BFS level is one minute. Track the count of fresh oranges; if any remain after the spread stops, return -1.

Problem

You are given an m x n grid where each cell can have one of three values: 0 for an empty cell, 1 for a fresh orange, or 2 for a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

Constraints

Examples

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

Complexity

Time: O(m*n) Space: O(m*n)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems