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

[英]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 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.

图表中的DFS将为您提供所有组。请注意,DFS本质上是递归的。

#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.

一旦你击中黑色单元格,如果可能的话,你将它“展开”到所有方向(类似于“floodfilling”)。您可以尽可能地扩展,并将所有访问过的单元格标记为“已访问”。在你这样做之后,你会计算你感染了多少个黑色细胞,你知道这个组有多大。检测到该组后,您将继续查看下一个“未访问的”黑色单元格。

#3


0  

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

您可以使用算法将连接组件标记与4连接


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/10/15/e2966a033bec05add668281609e73aa0.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号