最大矩形算法实现 [英] Maximum rectangle algorithm implementation

查看:197
本文介绍了最大矩形算法实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python实现 Dr. Dobbs的最大矩形算法(清单4)。它在大多数情况下都有效,但是一个具体案例给出了错误的结果,我无法弄清原因。

I'm trying to implement Maximum Rectangle Algorithm from Dr. Dobbs (Listing four) with Python. It works mostly, but one specific case gives wrong results and I cannot figure out why.

这是我的源代码:

from collections import namedtuple

Point = namedtuple('Point', ('X', 'Y'))

#Y      0  1  2      X
arr = [[0, 0, 0, ], #0
       [1, 0, 0, ], #1
       [0, 0, 1, ], #2
       ]

def area(ll, ur):
    if (ll.X < 0) or (ll.Y < 0) or (ur.X < 0) or (ur.Y < 0):
        return 0.
    return ((ur.X - ll.X) + 1) * ((ur.Y - ll.Y) + 1)

def update_cache(a, c, x):
    M = len(a[0])
    N = len(a)
    for y in range(M):
        if a[x][y] == 0:
            c[y] = c[y] + 1
        else:
            c[y] = 0

def mrp(a):
    best_ll = Point(-1, -1)
    best_ur = Point(-1, -1)
    M = len(a[0]) 
    N = len(a)
    c = [0 for x in range(M + 1)]
    stack = []
    for x in range(N-1, -1, -1):

        update_cache(a, c, x)        
        width = 0
        for y in range(M + 1):
            if c[y] > width:
                stack.append((y, width))                
                width = c[y]
            if c[y] < width:
                while True:
                    y0, w0 = stack.pop()
                    if (width * (y - y0)) > area(best_ll, best_ur):
                        best_ll = Point(x, y0)
                        best_ur = Point(x + width - 1, y - 1)
                    width = w0
                    if (c[y] >= width):
                        break
                width = c[y] 
                if width == 0:
                    stack.append((y0, width))
    return best_ll, best_ur

结果如下:

>>> mrp(arr)
(Point(X=0, Y=0), Point(X=1, Y=2))

如您所见,第一点是错误的,但我无法弄清楚它在哪里以及为什么会出错。更改arr可获得正确的结果。

As you can see, the first point is wrong, but I cannot figure out where and why it goes wrong. Changing the arr gives right results.

编辑::我注意到与文章相比,我更改了数组的值。这将更改update_cache中的比较。 0 =清除,1 =保留。我正在寻找结果(Point(X = 0,Y = 1),Point(X = 1,Y = 2))。

I noticed I've changed the values of the array compared to article. This changes the comparision in update_cache. 0=clear and 1=reserved. I'm looking for result (Point(X=0, Y=1), Point(X=1, Y=2)).

推荐答案

最后一个stack.append应该是:

Last stack.append should be:

stack.append((y0, w0))

这篇关于最大矩形算法实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆