Rotting Oranges

Medium Graph traversal BFS Matrix

Problem

A grid contains 0 (empty), 1 (fresh orange) and 2 (rotten orange). Every minute, any fresh orange that is four-directionally adjacent to a rotten one becomes rotten. Return the minimum minutes until every orange is rotten, or -1 if that is impossible.

Original: LeetCode 994: Rotting Oranges.

Examples

Example 1

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

Example 2

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

Example 3

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

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (1)
  1. LeetCode 994: Rotting Orangesleetcode.com