Problem · Array

Rotting Oranges

Learn this problem
MediumOtter.ai logoOtter.aiFULLTIMEONSITE INTERVIEW

Problem statement

You are given an m x n grid where 0 is an empty cell, 1 is a fresh orange, and 2 is a rotten orange. Every minute, each fresh orange that is orthogonally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes until no fresh orange remains. Return -1 if this is impossible.

Function

orangesRotting(grid: int[][]) → int

Examples

Example 1

grid = [[2,1,1],[1,1,0],[0,1,1]]return = 4

A breadth-first spread from the initial rotten orange reaches the last fresh orange after four minutes.

Example 2

grid = [[2,1,1],[0,1,1],[1,0,1]]return = -1

The fresh orange in the lower-left corner cannot be reached through orthogonal neighbors.

Example 3

grid = [[0,2]]return = 0

No fresh orange is present, so zero minutes are needed.

Constraints

  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2.
  • Adjacency is orthogonal: up, down, left, or right.
drafts saved locally
public int orangesRotting(int[][] grid) {
    // write your code here
}
grid[[2,1,1],[1,1,0],[0,1,1]]
expected4
checking account