【题目】
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)