This is part of image processing algorithm where more optimization is expected.
We have a large sparse matrix consisting of 0’s and 1’s. In this sparse matrix there are one or more dense region of 1’s. Lets say the whole matrix represents an image and 0 represent non-video areas and 1 represents video areas. Basically All nearby 1’s should be grouped together to find out the more approximate video region. So drawing a boundary around all 1’s will give exact video areas in a image.

As shown in the above matrix of 0’s and 1’s. There are 4 dense areas of 1’s. We have tried a naive approach which is of more time complexity and further improvements expected.
The approach we tried is converting all 0’s in a block size of 3*3 or 2*2 if the number of 1’s in the block are above a certain threshold value. But even this approach doesnt give us the exact boundary of video blocks.
So looking for a better algorithm which is good in both time and space complexity. Actually this calculation need to be done in real time so algorithm must have a very less time complexity. It would be great if we can achieve in O(n) linear time.
The usual approach here is to apply a sweep line algorithm.
Basically, it works as follows: Look at each column. If it consists of all zeros, move on to the next column. If it contains 1’s, save the smallest and largest vertical positions (they are likely candidates for rectangle coordinates). As you move the sweep line further, adjust your candidates accordingly. If you have found candidates and reach a line consisting of all zeros, your coordinate candidates are the actual coordinates of the rectangle.
You may as well (or additionally) sweep vertically and examine rows instead of columns.
Depending on the properties of your matrix (or your task), there are a lot of different possible solutions. Consider the following matrix:
How many rectangles does it contain? 1? 9? 4?
In your example, the two touching rectangles may as well be regarded as part of one larger rectangle.
Some advice: state your problem more clearly.