[leetcode]Maximal Rectangle @ Python

原题地址:https://oj.leetcode.com/problems/maximal-rectangle/

题意:Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

解题思路:找出矩阵中最大的矩形,矩形中只包含1。这道题需要利用上一道题(Largest Rectangle in Histogram)的结论。比如对于以下矩阵。

        0 0 0 0

        0 0 1 0

        0 1 1 0

        1 0 1 1

     对于这个矩阵,对于每一行,我们按照上一道题的算法求解一遍,最后得出的就是最大的矩阵。

代码:

class Solution:
    # @param matrix, a list of lists of 1 length string
    # @return an integer
    def largestRectangleArea(self, height):
        stack=[]; i=0; area=0
        while i<len(height):
            if stack==[] or height[i]>height[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*height[curr])
                i-=1
            i+=1
        while stack!=[]:
            curr=stack.pop()
            width=i if stack==[] else len(height)-stack[len(stack)-1]-1
            area=max(area,width*height[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))
        
        return maxArea
        

 

posted @ 2014-06-12 16:53  南郭子綦  阅读(3134)  评论(0编辑  收藏  举报