Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of "holes" in a bitmap

Consider a MxN bitmap where the cells are 0 or 1. '1' means filled and '0' means empty.

Find the number of 'holes' in the bitmap, where a hole is a contiguous region of empty cells.

For example, this has two holes:

11111  
10101  
10101  
11111  

... and this has only one:

11111  
10001  
10101  
11111

What is the fastest way, when M and N are both between 1 and 8?

Clarification: diagonals are not considered contiguous, only side-adjacency matters.

Note: I am looking for something that takes advantage of the data format. I know how to transform this into a graph and [BD]FS it but that seems overkill.

like image 915
florin Avatar asked Oct 26 '10 16:10

florin


People also ask

How do you count holes?

The stitch goes over threads. Four holes around the + that is the thread is how you count. The holes on one side of each stitch (Two holes) are the other side of the next stitch. So count the threads for placement, but stitch across them into the holes.

What are bitmap holes?

array of strings stored in strArr, which will be a 2D. matrix of 0 and 1's, and determine how many holes, or contiguous regions of O's, exist in the matrix.


2 Answers

You need to do connected component labeling on your image. You can use the Two-pass algorithm described in the Wikipedia article I linked above. Given the small size of your problem, the One-pass algorithm may suffice.

You could also use BFS/DFS but I'd recommend the above algorithms.

like image 74
Jacob Avatar answered Sep 22 '22 19:09

Jacob


This seems like a nice use of the disjoint-set data structure.
Convert the bitmap to a 2d array
loop through each element
if the current element is a 0, merge it with the set of one its 'previous' empty neighbors (already visited)
if it has no empty neighbors, add it to its own set

then just count the number of sets

like image 43
Sam Dufel Avatar answered Sep 22 '22 19:09

Sam Dufel