We are given a 2D integer matrix with and where where 0 represents an empty cell, 1 represents an a fresh orange and 2 represents a rotten orange.
The problem asks us to calculate the number of minutes after all oranges get rotten given, every 1 minute the 4-directional neighbours of a rotten orange also get rotten. We must return -1 if there’s a fresh orange left after doing the entire search.
This is a classic use case for a breadth-first search (BFS). We add all the rotten oranges to a search queue and then add neighbours of that node in every iteration. If the current node we are checking is a 0 (empty cell) or a 2 (rotten orange) we don’t add that to the queue, but if the current neighbour is a 1 (fresh orange) we change it to a 2.
Now, we can change it to a 2, because we know for a fact that it’s neighbour (the node that we just poped) is a rotten orange as we are putting only rotten oranges in the queue.
Code:
Python
Big O Analysis
-
Runtime
The runtime complexity here is since we would visit all nodes at least once. There’s an exceptional case where a part of the matrix gets secluded due of 0’s in which case we don’t have to visit them.
-
Memory
The memory usage is since we use a queue to store rotten oranges.
— A