直方图中的最大面积矩形。查找最大矩形的尺寸

时间:2018-03-13 05:00:19

标签: python algorithm data-structures dynamic-programming

我试图找到最大面积直方图,但我想跟踪最大矩形的高度和宽度。我通过初始化和跟踪全局宽度尝试了不同的方法但却无法做到。

这是我写过的最大区域直方图的代码。 使用此视频进行编码。 https://www.youtube.com/watch?v=RVIh0snn4Qc&t=888s

class Solution:
def largestRectangleArea(self, hist):
    stack=[]; i=0; area=0
    while i<len(hist):
        if stack==[] or hist[i]>hist[stack[len(stack)-1]]:
            stack.append(i)
        else:
            curr=stack.pop()
            width=i if stack==[] else i-stack[len(stack)-1]-1
            area=max(area,width*hist[curr])
            i-=1
        i+=1
    while stack!=[]:
        curr=stack.pop()
        width=i if stack==[] else len(hist)-stack[len(stack)-1]-1

        area=max(area,width*hist[curr])
    return area, 

def maximalRectangle(self, matrix):
    if matrix==[]: return 0
    a=[0 for i in range(len(matrix[0]))]; maxArea=0
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            a[j]=a[j]+1 if matrix[i][j]=='1' else 0

        maxArea=max(maxArea, self.largestRectangleArea(a)[0])
        print (self.largestRectangleArea(a))
    return maxArea


if __name__ == "__main__":
print( Solution().maximalRectangle([['1', '1', '0', '1', '0', '1'],
                                    ['0', '1', '0', '0', '1', '1'],
                                    ['1', '1', '1', '1', '0', '1'],
                                    ['1', '1', '1', '1', '0', '1']]))

1 个答案:

答案 0 :(得分:0)

将内置max操作替换为自己的实现 - 当您获得更好的结果时,请记住widthhist[curr])的值是最佳值(此时)。像这样:

  #area=max(area,width*hist[curr])
  newarea = width*hist[curr] 
  if (newarea>area):
        area = newarea
        bestw = width
        besth = hist[curr]