Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count groups of same cells in a 2d array?

Here's the example (counting black ones):

input:

enter image description here

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 recursive way? Thanks

like image 859
Patryk Avatar asked Oct 15 '12 18:10

Patryk


1 Answers

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.

like image 197
amit Avatar answered Nov 03 '22 13:11

amit