How can I find hole in a 2D matrix?

后端 未结 5 2202
死守一世寂寞
死守一世寂寞 2020-12-14 09:30

I know the title seems kind of ambiguous and for this reason I\'ve attached an image which will be helpful to understand the problem clearly. I need to find holes inside the

5条回答
  •  渐次进展
    2020-12-14 09:37

    Make some sort of a "LinkedCells" class that will store cells that are linked with each other. Then check cells on-by-one in a from-left-to-right-from-top-to-bottom order, making the following check for each cell: if it's neighbouring cell is black - add this cell to that cell's group. Else you should create new group for this cell. You should only check for top and left neighbour.
    UPD: Sorry, I forgot about merging groups: if both neighbouring cells are black and are from different groups - you should merege tha groups in one.

    Your "LinkedCells" class should have a flag if it is connected to the edge. It is false by default and can be changed to true if you add edge cell to this group. In case of merging two groups you should set new flag as a || of previous flags. In the end you will have a set of groups and each group having false connection flag will be "hole".

    This algorithm will be O(x*y).

提交回复
热议问题