FastPrepRotting Oranges
Problem · Array

Rotting Oranges

Learn this problem
MediumSalesforce logoSalesforceNEW GRADONSITE INTERVIEW
See Salesforce hiring insights

Problem statement

You are given a rectangular grid whose cells contain 0 for empty, 1 for a fresh orange, or 2 for a rotten orange.

For this exercise, assume every minute each fresh orange orthogonally adjacent to a rotten orange becomes rotten, and all changes in one minute happen simultaneously.

Return the minimum minutes until no fresh orange remains. Return -1 if that is impossible. Return 0 when no fresh orange exists initially.

Function

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

Examples

Example 1

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

The final fresh orange is reached by the fourth simultaneous breadth-first layer.

Example 2

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

The lower-left fresh orange is disconnected from every rotten orange.

Example 3

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

No fresh orange exists.

Constraints

  • 1 <= grid.length <= 500.
  • 1 <= grid[row].length <= 500.
  • Every row has the same length.
  • Each cell is 0, 1, or 2.

More Salesforce problems

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