LeetCode 85 Maximal Rectangle (Python详解及实现)

【题目】

Given a 2D binary matrix filled with 0'sand 1's, find the largest rectangle containing only 1's and return its area.

 

For example, given the following matrix:

 

1 0 1 0 0

1 0 1 1 1

1 1 1 1 1

1 0 0 1 0

Return 6.

 

给定一个由二进制组成的矩阵,找到仅仅包含1的最大矩形,并返回其面积。

 

【思路】

这一题的算法本质上和84题Largest Rectangle in Histogram一样,对每一行都求出每个元素对应的高度,这个高度就是对应的连续1的长度,然后对每一行都更新一次最大矩形面积。那么这个问题就变成了Largest Rectangle in Histogram。本质上是对矩阵中的每行,均依次执行84题算法。

 

【Python实现】

# -*- coding: utf-8 -*-

"""

Created on Wed Aug  9 15:34:39 2017

 

@author: Administrator

"""

class Solution(object):

   def maximalRectangle(self, matrix):

       """

       :type matrix: List[List[str]]

       :rtype: int

       """

       if  matrix == [] or len(matrix) ==0:

           return 0

       maxArea = 0

       heights = [0 for i in range(len(matrix[0]))]

       

       for i in range(len(matrix)):

           for j in range(len(matrix[i])):

                heights[j] = heights[j] + 1 ifmatrix[i][j] == '1' else 0 #计算高度值

           maxArea = max(maxArea,self.largestRectangleArea(heights))

           print(maxArea)

       return maxArea   

 

 

   

   def largestRectangleArea(self, heights):

       maxArea = 0

       stack = []

       i = 0

       while i < len(heights):

           if len(stack) == 0 or stack[-1] <= heights[i]:

                stack.append(heights[i])

           else:

                count = 0

                while len(stack) > 0 andstack[-1] > heights[i]:#height[i]小于栈顶元素

                    count += 1

                    maxArea = max(maxArea,int(stack[-1])*count)

                    stack.pop()#栈顶元素出栈

                while count > 0:#将当前height入栈

                    count -= 1

                    stack.append(heights[i])

                stack.append(heights[i])

           i += 1

       count = 1

       while len(stack) != 0:

           maxArea = max(maxArea, int(stack[-1])*count)

           stack.pop()

           count += 1

       return maxArea

   

if __name__ == '__main__':

    S= Solution()

   heights =["10100","10111","11111","10010"]

   maxarea = S.maximalRectangle(heights)

 

       

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值