Leetcode 994: Rotting Oranges

grid47
grid47
Exploring patterns and algorithms
Jul 30, 2024 8 min read

You are given an m x n grid where each cell can be empty, contain a fresh orange, or a rotten orange. Every minute, any fresh orange that is adjacent to a rotten orange becomes rotten. The task is to determine the minimum number of minutes required for all fresh oranges to rot. If this is not possible, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of a grid represented by a 2D array, where each element can be 0, 1, or 2.
Example: grid = [[2,1,1],[1,1,0],[0,1,1]]
Constraints:
• 1 <= m, n <= 10
• grid[i][j] can be 0, 1, or 2.
Output: Return the minimum number of minutes required for all fresh oranges to rot. If it's impossible, return -1.
Example: Output: 4
Constraints:
• The grid has at least one cell and at most 100 cells.
Goal: To calculate the minimum time required to rot all the fresh oranges using breadth-first search (BFS) from the rotten oranges.
Steps:
• Initialize a queue with all the positions of rotten oranges.
• Perform BFS, and for each rotten orange, check its 4-directional neighbors.
• If a fresh orange is found, make it rotten and add its position to the queue.
• Keep track of the minutes elapsed while processing each level of BFS.
• Return the number of minutes, or -1 if some fresh oranges cannot be rotted.
Goal: The constraints ensure that the grid will not be too large to handle with a breadth-first search approach.
Steps:
• 1 <= m, n <= 10
• The grid contains only 0, 1, or 2.
Assumptions:
• The grid will always contain at least one cell.
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Explanation: In this example, after 4 minutes all fresh oranges rot. The rotten orange at (0,0) spreads to adjacent cells and eventually rots all the fresh oranges.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus