Rotten Oranges
The problem
Given an n x m grid, where each cell has the following values :
2 - represents a rotten orange 1 - represents a Fresh orange 0 - represents an Empty Cell Every minute, if a fresh orange is adjacent to a rotten orange in 4-direction ( upward, downwards, right, and left ) it becomes rotten.
Return the minimum number of minutes required such that none of the cells has a Fresh Orange. If it's not possible, return -1.
Input: grid = [ [2, 1, 1] , [0, 1, 1] , [1, 0, 1] ] Output: -1 Explanation: Orange at (3,0) cannot be rotten.
Input: grid = [ [2,1,1] , [1,1,0] , [0,1,1] ] Output: 4 Explanation:
Input: grid = [[0,1,2],[0,1,2],[2,1,1]]
- 1 <= n, m <= 500
- grid[i][j] == 0 or 1 or 2
cpp
class Solution{
public:
int orangesRotting(vector<vector<int>> &grid) {
}
};java
class Solution {
public int orangesRotting(int[][] grid) {
}
}python
class Solution:
def orangesRotting(self, grid):javascript
class Solution {
orangesRotting(grid) {
}
}csharp
public class Solution {
public int OrangesRotting(int[][] grid) {
}
}go
func orangesRotting(grid [][]int) int {
}Stuck? Show a way to structure it+
- 01Enqueue every initially rotten orange and count all fresh oranges.
- 02Run BFS in four directions, infecting each fresh orange at most once.
- 03Track the infection time by BFS level or store a timestamp with each queued cell.
- 04Return the elapsed time when the fresh count reaches zero; otherwise return -1.
Reference answer
Then expect these follow-ups
How would you return the minute at which every reachable orange rots?
Tests: BFS state design
Why is running BFS independently from each rotten orange inefficient?
Tests: complexity analysis
Hiring now
Meesho has 33 open roles right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Deputy Manager- FP&A
Bangalore, Karnataka
Security Engineer III - Infra Security
Bangalore, Karnataka
Product Manager I
Bangalore, Karnataka
Next question