Leetcode练习(Python):数组类:第85题:给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

题目:
给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
思路:
使用head和tail来构建以某点为基准的矩形的宽,使用height来定义以某点为基准的矩形的高。
程序:
class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        if not matrix:
            return 0
        row = len(matrix)
        column = len(matrix[0])
        if row <= 0:
            return 0
        if column <= 0:
            return 0
        head = [-1] * column
        tail = [column] * column
        height = [0] * column
        result = 0
        for index1 in range(row):
            current_head = -1
            current_tail = column
            for index2 in range(column):
                if matrix[index1][index2] == "1":
                    height[index2] += 1
                else:
                    height[index2] = 0
            for index2 in range(column):
                if matrix[index1][index2] == "1":
                    head[index2] = max(head[index2], current_head)
                else:
                    head[index2] = -1
                    current_head = index2
            for index2 in range(column - 1, -1, -1):
                if matrix[index1][index2] == "1":
                    tail[index2] = min(tail[index2], current_tail)
                else:
                    tail[index2] = column
                    current_tail = index2
            for index2 in range(column):
                result = max(result, (tail[index2] - head[index2] - 1) * height[index2])
        return result
posted on 2020-04-24 10:36  桌子哥  阅读(3252)  评论(0编辑  收藏  举报