zoukankan      html  css  js  c++  java
  • [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
            
  • 相关阅读:
    Java 处理 multipart/mixed 请求
    SpringBoot 动态更新 resources 目录的文件
    dubbo 2.7.0 中缺乏 <dubbo:annotation /> 的解决方案
    设计模式 — 终章.
    代理模式
    状态模式.
    第七节、双目视觉之空间坐标计算
    第六节、双目视觉之相机标定
    经典项目博客集合
    第五节、轮廓检测、直线和圆、多边形检测
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3784252.html
Copyright © 2011-2022 走看看