Leetcode 85:最大矩形(超详细的解法!!!)

版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/86237801

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例:

输入:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
输出: 6

解题思路

这个问题实际上就是之前Leetcode 84:柱状图中最大的矩形(超详细的解法!!!)问题的拓展。我们可以将这个问题转化为之前的那个问题,也就是我们将此时输入矩阵的每一行以上的所有行看成是一个柱状图。

我们最后会得到上面这个直方图矩阵。

class Solution:
    def maximalRectangle(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        if not matrix:
            return 0
        
        r, c = len(matrix), len(matrix[0])
        height, res = [0]*c, 0
        for row in matrix:
            for i in range(c):
                height[i] = height[i] + 1 if row[i] == '1' else 0
            res = max(self.helper(height), res)
            
        return res
    
    def helper(self, row):
        stack = list()
        len_row, i = len(row), 0
        res = 0
        while i < len_row:
            if not stack or row[stack[-1]] <= row[i]:
                stack.append(i)
                i += 1
            else:
                k = stack.pop()
                res = max(res, row[k]*((i-stack[-1]-1) if stack else i))
        while stack:
            k = stack.pop()
            res = max(res, row[k]*((i-stack[-1]-1) if stack else i))
        return res

非常酷!!!我们可以将上述的代码继续简化(参考之前问题的最后一种写法)

class Solution:
    def maximalRectangle(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        if not matrix:
            return 0
        
        r, c = len(matrix), len(matrix[0])
        height, res = [0]*(c+1), 0
        for row in matrix:
            for i in range(c):
                height[i] = height[i] + 1 if row[i] == '1' else 0
            
            stack = [-1]
            for idx, val in enumerate(height):
                while val < height[stack[-1]]:
                    h = height[stack.pop()]
                    res = max(res, h*(idx - stack[-1] - 1))
                    
                stack.append(idx)
                
        return res

reference:

https://leetcode.com/problems/maximal-rectangle/discuss/29065/AC-Python-DP-solutioin-120ms-based-on-largest-rectangle-in-histogram

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/86237801