Open In App

Find all rectangles filled with 0

We have one 2D array, filled with zeros and ones. We have to find the starting point and ending point of all rectangles filled with 0. It is given that rectangles are separated and do not touch each other however they can touch the boundary of the array.A rectangle might contain only one element.

Examples: 



input = [
            [1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 0, 0, 0, 1],
            [1, 0, 1, 0, 0, 0, 1],
            [1, 0, 1, 1, 1, 1, 1],
            [1, 0, 1, 0, 0, 0, 0],
            [1, 1, 1, 0, 0, 0, 1],
            [1, 1, 1, 1, 1, 1, 1]
        ]


Output:
[
  [2, 3, 3, 5], [3, 1, 5, 1], [5, 3, 6, 5]
]

Explanation:
We have three rectangles here, starting from 
(2, 3), (3, 1), (5, 3)

Input = [
            [1, 0, 1, 1, 1, 1, 1],
            [1, 1, 0, 1, 1, 1, 1],
            [1, 1, 1, 0, 0, 0, 1],
            [1, 0, 1, 0, 0, 0, 1],
            [1, 0, 1, 1, 1, 1, 1],
            [1, 1, 1, 0, 0, 0, 0],
            [1, 1, 1, 1, 1, 1, 1],
            [1, 1, 0, 1, 1, 1, 0]
        ]


Output:
[
  [0, 1, 0, 1], [1, 2, 1, 2], [2, 3, 3, 5], 
  [3, 1, 4, 1], [5, 3, 5, 6], [7, 2, 7, 2], 
  [7, 6, 7, 6]
]

Step 1: Look for the 0 row-wise and column-wise
Step 2: When you encounter any 0, save its position in output array and using loop change all related 0 with this position in any common number so that we can exclude it from processing next time.
Step 3: When you change all related 0 in Step 2, store last processed 0’s location in output array in the same index.
Step 4: Take Special care when you touch the edge, by not subtracting -1 because the loop has broken on the exact location. 

Below is the implementation of above approach: 























Output
[[2, 3, 3, 5], [3, 1, 5, 1], [5, 3, 6, 5]]

Time Complexity: O(x*y). 
Auxiliary Space: O(x*y).

Asked in Intuit


Article Tags :