Description
Given a rows x cols binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
Constraints:
• rows == matrix.length
• cols == matrix[i].length
• 0 <= row, cols <= 200
• matrix[i][j] is ‘0’ or ‘1’.
Example
Example 1:
Input: matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = []
Output: 0
Example 3:
Input: matrix = [[“0”]]
Output: 0
Example 4:
Input: matrix = [[“1”]]
Output: 1
Example 5:
Input: matrix = [[“0”,“0”]]
Output: 0
Submissions
解题思路与84题类似,首先遍历每一行,建立一个列表h,以第一行为底,用来保存在新遍历每一行之后,可行的高度,这个高度不是简单的累加,而是当遇到不是断层时,变为0。从第一行开始,每行都要计算最大面积,直到遍历到最后一行。
h表示遍历到当前行的可行高度,每一行都要计算最大面积,而当遇到0时,可行高度不能保持原数,应归零,再继续用可行高度计算最大面积。temp为递增栈,存储连续的增强下标。
实现代码如下:
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix :
return 0
n=len(matrix)
m=len(matrix[0])
h=[0]*m
ms=0
for i in range(n):
temp=[]
for j in range(m+1):#设置m+1是为了不漏计算,像上一题我们是+[0],一样的效果
if j<m:
h[j]=(h[j]+1)if matrix[i][j]=='1' else 0 #若遇到0,则高度为0,看图解
while temp and (j==m or h[temp[-1]]>h[j]): #当出现不增墙
height=h[temp.pop()]
ms=max(ms,height*(j-1-(temp[-1] if temp else -1)))
temp.append(j) #将新不增墙加入递增栈temp
return ms