Rabbit House | Google Kickstart 2021 Round A
Barbara got really good grades in school last year, so her parents decided to gift her with a pet rabbit. She was so excited that she built a house for the rabbit, which can be seen as a 2D grid with RR rows and CC columns.
Rabbits love to jump, so Barbara stacked several boxes on several cells of the grid. Each box is a cube with equal dimensions, which match exactly the dimensions of a cell of the grid.
However, Barbara soon realizes that it may be dangerous for the rabbit to make jumps of height greater than 11 box, so she decides to avoid that by making some adjustments to the house. For every pair of adjacent cells, Barbara would like that their absolute difference in height be at most 11 box. Two cells are considered adjacent if they share a common side.
As all the boxes are superglued, Barbara cannot remove any boxes that are there initially, however she can add boxes on top of them. She can add as many boxes as she wants, to as many cells as she wants (which may be zero). Help her determine what is the minimum total number of boxes to be added so that the rabbit’s house is safe.
Given a matrix of R rows and M columns. Make the absolute difference between the adjacent cells less than or equal to 1 by only increasing the cell value. The total increment done on cells should be minimized. The task is to return the minimum increment operations done.
Input: [[0 0 0],
[0 2 0],
[0 0 0]]
Explanation: the cell in the middle of the grid has an absolute difference in height of 2, the height of all its four adjacent cells is increased by exactly 1 unit so that the absolute difference between
any pair of adjacent cells will be at most 1. Resultant matrix will be:
[[0 1 0],
[1 2 1],
[0 1 0]]
Input: [[1 0 5 4 2],
[1 5 6 4 8],
[2 3 4 2 1],
[2 3 4 9 8]]
Explanation: Resultant matrix will be: [[3 4 5 6 7],
[4 5 6 7 8 ],
[5 6 7 8 7],
[6 7 8 9 8]]
Approach: Given problem can be solved using multisource dijkstra’s algorithm. The approach is to store the cells with the largest values in a priority queue, pop out the priority queue one by one and update the adjacent cells accordingly, while updating the cell value we will also update our priority queue.
Below is the implementation of the above approach:
Time Complexity: O(RM * Log(RM))
Auxiliary Space: O(RM)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.