### 如何计算二维数组中相同单元的组？

#### [英]How to count groups of same cells in a 2d array?

Here's the example (counting black ones):

input:

output:

``````5 4 // 5 groups (4 squares each)
1 1 // 1 group containing 1 square
``````

For Now, I can't think of anything better than a painfull for iteration. Would it be possible to get these groups in a recursion way? Thanks

## 3 个解决方案

### #1

2

Set all black squares as nodes. Connection between black squares (if the squares are next to each other) will be an edge.

This gives you a graph.

A DFS in the graph will get you all the groups. Note that DFS is recursive by nature.

### #2

0

At the beginning, each cell be "unvisited".

I would iterate through the cells until you meet an "unvisited" black cell. Each white cell you hit up to that point

Once you hit a black cell, you "expand" it to all directions if possible (similar to "floodfilling"). You expand as long as you can and mark all the visited cells as "visited". After you did that, you count how many black cells you infected, and you know how big the group was. After detecting the group, you go on to the next "unvisited" black cell.

### #3

0

You can use algorithm for connected component labeling with 4-connectivity