Your "holes" are actually connected components of zeroes within a graph formed by the grid. Each element has four neighbours. Find connected components with BFS or DFS, pick the largest one, or sum them up. This algorithm works in O(N)
, where N
is the number of elements in the matrix.
You can also use more specific labeling algorithm, that works on these types of graphs, usually appearing from images. Labeling will also enumerate all the connected components for you.
If you are not interested in connected components, that are not completely surrounded by ones, like this:
[[1,0,1,1],
[1,1,1,1],
[1,0,0,1],
[0,0,1,1], // <-- Note zero in the beginning
[1,1,1,0]]
You can expand your matrix with border of zeros, like this:
[[0,0,0,0,0,0]
[0,1,0,1,1,0],
[0,1,1,1,1,0],
[0,1,0,0,1,0],
[0,0,0,1,1,0],
[0,1,1,1,0,0],
[0,0,0,0,0,0]]
And then ignore the outer connected component. In this example, there are no more components, so the answer is zero.