Given a 2D binary matrix filled with 0’s and 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.
思路
利用LeetCode-84. Largest Rectangle in Histogram的结果,把每一行的每一列元素都当做一个直方块,计算n次最大直方块面积,找出其中最大值,n为题目中二维数组的行数。
难点
如何确定当前行的每一列直方块高度,使用以下策略:
- 将每列的高度初始化为0
- 当前元素为1,则在原先的高度上加1
- 当前元素为0,则重置为0
注意:官网上的测试案例有空数组,所以第一行要加上对它的判断。
此题还有使用动态规划的解法,具体见下方连接。
https://www.cnblogs.com/lupx/archive/2015/10/20/leetcode-85.html
Java实现
class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix.length==0||matrix[0].length==0)
return 0;
int res=0;
int row=matrix.length;
int col=matrix[0].length;
int[] heights=new int[col];
for(int i=0;i<col;++i)
heights[i]=0;
for(int i=0;i<row;++i)
{
for(int j=0;j<col;++j)
{
if(matrix[i][j]=='0')
heights[j]=0;
else
heights[j]+=1;
}
int maxArea=largestRectangleArea(heights);
if(res<maxArea)
res=maxArea;
}
return res;
}
public int largestRectangleArea(int[] heights) {
Stack<Integer> s=new Stack<>();
int maxArea=0;
int currentMaxArea=0;
int tp=0;
int i=0;
while(i<heights.length)
{
if(s.empty()||heights[s.peek()]<=heights[i])
{
s.push(i++);
}
else
{
tp=s.peek();
s.pop();
currentMaxArea=heights[tp]*(s.empty()?i:(i-s.peek()-1));
if(currentMaxArea>maxArea)
maxArea=currentMaxArea;
}
}
while(!s.empty())
{
tp=s.peek();
s.pop();
currentMaxArea=heights[tp]*(s.empty()?i:(i-s.peek()-1));
if(currentMaxArea>maxArea)
maxArea=currentMaxArea;
}
return maxArea;
}
}