使用 R 在二进制矩阵中查找模式
我有一个 nxn 对称二进制矩阵,我想找到左上角和右下角为 0,右上角和左下角为 1 的最大矩形(区域)。如果我只是用循环来做,从最大到最小检查所有矩形,则 n=100 需要“天”。有人知道如何有效地做到这一点吗?
多谢 !
I have a nxn symetrical binary matrix and I want to find the largest rectangle (area) with 0 at the top-left and bottom-right corners and 1 at the top-right and bottom-left corner. If I just do it with loops, checking all the rectangles from the biggest to the smallest it takes "days" for n=100. Does anyone have an idea to do it efficiently?
Thanks a lot !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
感谢您的回答。我使用的矩阵是随机 Erdos-Renyi 图的邻接矩阵。但可以采用任意随机对称二元矩阵来测试它。到目前为止,我使用了 4 个嵌套循环:
thanks for your answers. Matrices I use are adjacency matrices of random Erdos-Renyi graphs. But one can take any random symetrical binary matrix to test it. Until now, I use 4 nested loops :
您现在可以尝试以下方法。它不需要对称性,并且为了效率而将所有非零元素视为非零元素。
它循环遍历这些,假设 1 的数量少于零。 (您可能希望在相反的情况下循环零,并且零比一少。)
这种方法可能不是最佳的,因为即使尽早识别了最大的框,它也会循环所有的零。在这种情况下,您可以设计一个巧妙的停止条件来短路循环。
但对于
n = 100
来说它仍然很快,在我的机器上需要不到半秒,即使 1 和 0 出现的比例大致相等(最坏的情况):Here's an approach that you can try for now. It doesn't require symmetry, and it treats all nonzero elements like ones for efficiency.
It loops over the ones, assuming that there are fewer ones than zeros. (You would want to loop over zeros in the reverse case with fewer zeros than ones.)
This approach probably isn't optimal, since it loops over all of the ones even if the largest box is identified early. You can devise a clever stopping condition to short-circuit the loop in that case.
But it is still fast for
n = 100
, requiring less than half of a second on my machine, even when ones and zeros occur in roughly equal proportion (the worst case):