
In this problem, you are provided with a matrix (grid) of dimensions m x n, representing a grid where each cell can hold either an empty cell (0), a fresh orange (1), or a rotten orange (2). The task is to simulate the process by which the rotten oranges contaminate the fresh ones. The contamination spreads to fresh oranges that are adjacent in the four cardinal directions (up, down, left, right) at the rate of one minute per step.
Your objective is to determine the minimum number of minutes required for all fresh oranges to become rotten, if possible. If there are fresh oranges that cannot be contaminated by the rotten ones due to isolation, you should return -1 to indicate this impossibility.
Input:
Output:
Input:
Output:
Explanation:
Input:
Output:
Explanation:
m == grid.lengthn == grid[i].length1 <= m, n <= 10grid[i][j] is 0, 1, or 2.Given the nature of the problem, which involves spreading from multiple sources over time, a breadth-first search (BFS) strategy using a queue can be effectively implemented here. The intuition behind using BFS is that it perfectly models situations involving levels or steps (in this case, minutes):
1), convert it to rotten (2) and add its position to the queue for further processing in the subsequent minute (next level of BFS).-1.This BFS conceptualization ensures that the contamination wave propagates efficiently, and the counter provides the earliest minute each orange turns rotten. In instances where the matrix is initially free of fresh oranges or contains only isolated fresh oranges, the condition is quickly detected and handled appropriately, either by returning 0 or -1.
The Rotting Oranges problem involves a grid where each cell can contain an orange that can be fresh, rotten, or empty. The goal is to determine the minimum number of minutes required for all fresh oranges to become rotten, given that a rotten orange at each minute turns its adjacent fresh oranges rotten.
The given solution in Java provides an efficient approach for solving this problem:
Define the propagateRot function to simulate the rotting process for each minute:
steps array to represent possible movements: up, right, down, and left.Define the orangesRotting function to manage the propagation over multiple minutes and determine if all oranges can rot:
propagateRot while tracking each minute until no fresh oranges can be rotten.By carefully managing the simulation of each minute and checking termination conditions, this solution efficiently determines how quickly all oranges can rot or if it's impossible, ensuring optimal time usage and clarity in processing the grid-based simulation.
0 Comments
Be the first to comment and share your perspective with the community.