这个题和Largest rectangle in histogram有异曲同工之妙, 把每一行上面的矩形看成是histogram就行了
代码如下:
public class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix==null||matrix.length==0)
return 0;
int maxArea=0,m=matrix.length,n=matrix[0].length;
for(int i=0;i<m;i++){
Stack<Integer> heightStack=new Stack<Integer>();
Stack<Integer> indexStack=new Stack<Integer>();
for(int j=0;j<n;j++){
int hIndex=i,h=0;
int[] heights=new int[n];
while(hIndex>=0&&matrix[hIndex--][j]=='1')
h++;
heights[j]=h;
if(heightStack.isEmpty()||heights[j]>=heightStack.peek()){
heightStack.add(heights[j]);
indexStack.add(j);
}else{
//这个index非常重要,是下面用来计算的
int index=0;
while(!heightStack.isEmpty()&&heightStack.peek()>heights[j]){
index=indexStack.pop();
int area=(j-index)*heightStack.pop();
maxArea=area>maxArea?area:maxArea;
}
heightStack.add(heights[j]);
indexStack.add(index);
}
}
while(!heightStack.isEmpty()){
int area=(n-indexStack.pop())*heightStack.pop();
maxArea=area>maxArea?area:maxArea;
}
}
return maxArea;
}
}
本文介绍了一种求解矩阵中最大全1矩形面积的方法,该方法将每行视为直方图,并通过堆栈来记录高度和索引,以此找到最大的矩形面积。
918

被折叠的 条评论
为什么被折叠?



