題目:
給定一個無序矩陣,只包含0 和1 兩種元素,求只包含1的最大子矩陣的大小。
[leetcode85]https://leetcode.com/problems/maximal-rectangle/
思路:
有了求解直方圖最大矩形的[算法原型]http://www.lxweimin.com/p/b871972747c0 之后,這個問題就方便許多。
可以考慮必須以某一行為底的最大1子矩陣,這樣所有行為底的最大即為所求。
算法步驟
注意以求解某行為底怎么求。用一個數(shù)組h來作為輔助數(shù)組.h[i]為這行的第i列往上有多少個連續(xù)的1,如果這行的i位置為0,則h[i]=0,否則h[i]=h[i]+1。
public class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix==null||matrix.length==0||matrix[0].length==0)
return 0;
int res=0;
int[] h=new int[matrix[0].length];
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
h[j]=matrix[i][j]=='0'?0:h[j]+1;
}
res=Math.max(res,largestRectangleArea(h));
}
return res;
}
public int largestRectangleArea(int[] heights) {
if(heights==null||heights.length==0)
return 0;
int res=0;
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<heights.length;i++){
while(!stack.isEmpty()&&heights[i]<=heights[stack.peek()]){
int cur=stack.pop();
int left=stack.isEmpty()?-1:stack.peek();
res=Math.max(res,(i-left-1)*heights[cur]);
}
stack.push(i);
}
while(!stack.isEmpty()){
int cur=stack.pop();
int left=stack.isEmpty()?-1:stack.peek();
res=Math.max(res,(heights.length-left-1)*heights[cur]);
}
return res;
}
}