Time Needed to Rot All Oranges šŸŠ

beginner
16 min

Time Needed to Rot All Oranges šŸŠ

Welcome to this comprehensive lesson on Data Structures and Algorithms! Today, we'll dive into a fascinating problem called "Time Needed to Rot All Oranges".

Let's begin with a simple scenario: Imagine you have a 3D grid filled with oranges, and each orange has a freshness level. The goal is to rotate this grid in such a way that all the oranges become rotten or all the oranges are eaten away.

Understanding the Problem šŸ“

In this problem, we are given a m * n * k grid where m represents the number of rows, n the number of columns, and k the number of layers (z-axis). Each cell in the grid can contain three values:

  • -1: empty cell
  • 0: fresh orange
  • 1: rotten orange

The rules are as follows:

  1. A fresh orange turns rotten in one hour.
  2. A rotten orange continues to be rotten for 2 hours.
  3. A rotten orange spreads its freshness to the adjacent fresh oranges (maximum 8) in the next hour.

The task is to find the minimum time needed to rot all the oranges in the grid.

Solving the Problem šŸŽÆ

We'll implement a Breadth-First Search (BFS) algorithm to solve this problem. BFS is a popular algorithm used for traversing or searching graphs or trees, which is perfect for our situation as we're dealing with a grid.

Here's a step-by-step breakdown of the algorithm:

  1. Initialize a queue to keep track of the rotten oranges that need to be processed.
  2. Start from each rotten orange and enqueue them into the queue.
  3. Perform a BFS traversal on the grid starting from the rotten oranges in the queue.
  4. For each fresh orange encountered during the BFS, enqueue it for the next hour.
  5. Increment the time by 1 for each operation (dequeueing a rotten orange, processing a fresh orange, or enqueuing a fresh orange).
  6. The algorithm terminates when the queue is empty, and all the oranges are rotten.

Code Example šŸ’»

Let's take a look at a Python code example implementing the BFS algorithm:

python
import collections def rot_oranges(grid): m, n, k = len(grid), len(grid[0]), len(grid[0][0]) queue, fresh = [], collections.defaultdict(int) # Initialize the queue with all the rotten oranges for i in range(m): for j in range(n): for z in range(k): if grid[i][j][z] == 1: queue.append((i, j, z)) # BFS starts here hours = 0 dx, dy, dz = [0, 0, 1], [0, 1, 0], [1, 0, 0] while queue: size = len(queue) for _ in range(size): x, y, z = queue.pop(0) # Mark the current orange as rotten grid[x][y][z] = 2 # Increment the freshness count for each neighbor for d_x, d_y, d_z in zip(dx, dy, dz): nx, ny, nz = x + d_x, y + d_y, z + d_z if nx >= 0 and nx < m and ny >= 0 and ny < n and nz >= 0 and nz < k: if grid[nx][ny][nz] == 0: fresh[(nx, ny, nz)] += 1 # Enqueue the fresh oranges for the next hour for pos, count in fresh.items(): if count > 0: queue.append(pos) fresh[pos] -= 1 # Increment the time hours += 1 # Check if all oranges are rotten for i in range(m): for j in range(n): for z in range(k): if grid[i][j][z] == 0: return -1 return hours

This Python function takes a list of lists of lists (3D list) as input and returns the minimum time needed to rot all the oranges or -1 if it's impossible.

Quiz 🧠

That's it for today's lesson! We've learned about the Time Needed to Rot All Oranges problem and implemented a BFS algorithm to solve it. In the next lesson, we'll explore more about Data Structures and Algorithms, so stay tuned! šŸš€

šŸ’” Pro Tip: Practice with different grid sizes and different initial states to get a better understanding of the problem.

šŸ“ Note: It's important to understand the problem constraints and rules before diving into the solution implementation. This will help you think more clearly and write efficient code.

āœ… Congratulations on completing this lesson! I hope you found it helpful and engaging. See you in the next one! šŸŠšŸŽ‰