查找矩阵中的面积数
假设我有一个类似这样的矩阵:
1 1 1 0 0 0
1 1 1 0 0 1
0 0 0 0 0 1
如果两个“1”彼此相邻(仅水平和垂直),因此属于同一区域。我需要找出矩阵中有多少个这些区域。您可以看到该矩阵中有两个区域为“1”。我已经尝试解决这个问题几个小时了,但是代码变得非常大而且令人厌恶。有没有我可以采用的算法来解决这个问题?
Assume I have a matrix something like this :
1 1 1 0 0 0
1 1 1 0 0 1
0 0 0 0 0 1
If two '1' are next to each other (horizontally and vertically only) and therefore belong to the same area. I need to find how many of these areas are there in a matrix. You can see that there's two areas of '1' in this matrix. I've been trying to solve this for hours now but the code gets really big and disgusting. Are there any algorithms out there I could adopt for this problem ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您并不真正关心:
保持输入矩阵完整
性能和优化
,那么这是我在C中对此问题的看法:
一旦当它遇到
1
时,它会递归地扩展所有相邻的1
元素,对它们进行计数并将它们转换为0
。如果该区域的大小大于IGN
,则将其考虑在内。注意:
如果需要保留原始矩阵,则必须使用副本进行输入。
如果您打算使用它,您可能应该将此代码转换为从参数获取数组及其大小的函数。应该避免
main()
中的全局变量和算法实现,但我在这种情况下例外,因为它降低了代码的复杂性并使算法更加清晰。将
IGN
设置为1
时,单独的元素不被视为区域。将IGN
更改为0
也会得到这些。循环中的
if (A[j][i] == 1)
条件并不是严格必要的,但它通过避免不必要的函数调用来作为次要优化,尽管编译器可能会进行优化使其冗余。您可以轻松修改它以获取每个区域中的元素列表。
If you don't really care about:
Keeping the input matrix intact
Performance and optimisations
then here's my take on this problem in C:
Once it encounters a
1
, it recursively expands over all neighbouring1
elements, counting them and turning them into0
. If the size of the area is larger thanIGN
, then it is taken into account.Notes:
If you need to keep the original matrix, you would have to use a copy for input.
If you plan on using this, you should probably turn this code into functions that get the array and its size from their parameters. Global variables and algorithm implementations in
main()
should be avoided, but I made an exception in this case because it reduces the complexity of the code and allows the algorithm to be more clear.With
IGN
set to1
, lone elements are not considered an area. ChangingIGN
to0
will get those too.The
if (A[j][i] == 1)
conditional in the loop is not strictly necessary, but it serves as a minor optimisation by avoiding unnecessary function calls, although compiler optimisations probably make it redudant.You can easily modify this to get a listing of the elements in each area.
这有帮助吗?我假设“相同区域”意味着这些点属于相同的连接组件。
http://en.wikipedia.org/wiki/Connected_Component_Labeling
Would this help? I assume that with "same area" you mean that the points belong to same connected component.
http://en.wikipedia.org/wiki/Connected_Component_Labeling
这个 python 函数应该可以解决问题(它在你的示例和我随机编写的其他一些示例中都可以):
This python function should do the trick (it does on your example and on some others I randomly made up):
我尝试过使用 DFS 算法方法的 python 实现时间复杂度为 O(M x N)。该函数的输入是一个 M*N 列表。
I have tried a python implementation that uses DFS algorithmic approach & works with time complexity O(M x N). Input for the function is a M*N list.
这是Java实现
这是测试用例
Here is the Java implementation
Here is the test case