码迷,mamicode.com
首页 > 其他好文 > 详细

Maximal Rectangle

时间:2016-06-16 17:34:01      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

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

Subscribe to see which companies asked this question.

这题看起来和max square 是一样的题目,但是尝试用max square 的DP来做无法得出.主要是上一个右下角点定到的最大面积在下一次无法帮助相邻点直接得到最大rectangle. 3*4 == 2*6.

实际如果使用DP解的话,是一个3维DP,f[i,j,k]对于坐标为i,j的点查找左上长为k的最大宽,之后进行转换.转换方程为:实际这题类似于Largest Rectangle in Histogram

的做法,即对矩阵的每一行,纵向连续为1的地方朝上都形成了一个bar.每一行更新这个bar的高度的过程遵从DP, 每一行都求出一个最大的矩形面积.即循环调用单调栈解法.

时间复杂度为O(m*n),空间复杂度为O(max(m,n))宽.栈和height的空间复杂度做一个比较,代码如下:

class Solution(object):
    def maximalRectangle(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        #f[i][j] must have height and width together
        if not matrix or not matrix[0]:
            return 0
        height = [int(n) for n in matrix[0]]
        maxRec = 0
        for i in xrange(0,len(matrix)):
            maxRec = max(maxRec, self.helper(matrix, height,i))
        return maxRec
             
    def helper(self, matrix, height, i): #largest rectange higher or equal than this line
        stack = []
        area = 0
        for j in xrange(len(height)+1):
            curt = height[j] if j < len(height) else -1
            while stack and curt <= height[stack[-1]]:
                h = height[stack.pop()]
                w = j if not stack else j - stack[-1] - 1
                area = max(area, h*w)
            stack.append(j)
        if i!= len(matrix)-1:
            for j in xrange(len(height)):
                if matrix[i+1][j] == ‘1‘:
                    height[j] += 1
                else:
                    height[j] = 0
        return area

Maximal Rectangle

标签:

原文地址:http://www.cnblogs.com/sherylwang/p/5591443.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!