![]() |
VOOZH | about |
Pablo has a square chocolate Box of size n x n in which a variety of healthy chocolates are present denoted by 'H' initially but he finds out that some of the chocolates are rotten and unhealthy denoted by 'U'. In one day the rotten chocolates make all its neighboring chocolates unhealthy. This goes on and on until all chocolates present in the chocolate box become Unhealthy to eat. Find out the number of days in which the whole chocolate box becomes Unhealthy.
(Note: It is guaranteed that at least one of the chocolate is Unhealthy)
Examples:
Input : n = 3 H H H H U H H H H Output : 1 Only 1 day is required to turn all the chocolates unhealthy in the chocolate box. Input : n = 4 H H H U H H H H H U H H H H H H Output : 2 Explanation: In first day chocolate at (0, 0), (0, 1), (2, 3), (3, 3) will remain healthy and in the second day all the chocolates will become unhealthy.
Asked in Amazon, Accolite, and Arcesium.
Brute Force Approach:
Initialize a flag = 1. Use a while loop, inside that while searching for an H (searching requires O(n^2) time complexity if we are unable to find an H in the 2-D character array stop incrementing the day counter and set the flag as 0 to break the loop.
Below is the implementation of the above approach:
number of days taken : 2
Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient Approach (Uses BFS):
In this approach, declare a queue which inputs pairs that corresponds to the index of the unhealthy chocolates, and then as soon as the index (-1, -1) is reached we increment the numdays counter. This Solution is basically based on calculating levels in level order traversal (Iterative version) of a binary tree in which we push the initial indexes of the unhealthy chocolates instead of the root node and increment numdays instead of the level counter as soon as the index (-1, -1) is reached instead of NULL. As soon as the counter of the flag reaches 2 we break the loop denoting that queue has encountered two consecutive (-1, -1) pairs.
Below is the implementation of the above approach:
number of days taken : 2
Time Complexity: O(n2)
Auxiliary Space: O(n2)