Rotting Oranges
Rotting Oranges
You are given an m x n grid where each cell can have one of three values:
0representing an empty cell,1representing a fresh orange, or2representing 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.
Examples
Example 1:
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Explanation: The rotten orange at (0,0) spreads to adjacent
fresh oranges each minute. After 4 minutes, all oranges are rotten.Example 2:
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange at (2,2) can never be reached because
it is isolated from the rotten orange.Example 3:
Input: grid = [[0,2]]
Output: 0
Explanation: There are no fresh oranges, so 0 minutes are needed.Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 10grid[i][j]is0,1, or2
Expected Complexity
- Time: O(m * n)
- Space: O(m * n)
MEDIUM
Graphs
BFS
Multi-Source BFS
Islands / Flood Fill
Intermediate
0 views
Solution
Hints
Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium
This section is available for CodeSnatch Premium members only.
