[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
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM