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.
找到矩阵中的最大全1矩阵
第一种方法,先从matrix[0][0]开始作为起始点start,然后从stasrt左至右、上至下遍历,matrix[i][j]作为end,计算每个矩阵面积。对于每一行,只要该行任意end不能构成全1矩阵,则该行end右边的点都不能构成全1矩阵,不需要遍历。
public static int maximalRectangle(char[][] matrix) {
if(matrix == null ||matrix.length<1)return 0;
int row = matrix.length;
int col = matrix[0].length;
int max=0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
for(int k=i;k<row;k++){
for(int y=j;y<col;y++){
int temp=area(i,j,k,y,matrix);
if(temp<0){
break;
}
else
max=max>temp?max:temp;
}
}
}
}
return max;
}
public static int area(int x1,int y1,int x2,int y2,char[][] matrix){
for(int i=x1;i<=x2;i++){
for(int j=y1;j<=y2;j++){
if(matrix[i][j]=='0')
return -1;
}
}
return (x2-x1+1)*(y2-y1+1);
}
第二种方法,借用84直方图求最大矩阵方法,对于矩阵每一层,往上构成直方图,比如第三层,就构成一个1,1,2,2,2的直方图,那么最大面积就为6,对每一层调用直方图面积即可求出最大值
public static int maximalRectangle(char[][] matrix) {
if(matrix == null ||matrix.length<1)return 0;
int row = matrix.length;
int col = matrix[0].length;
int max=0;
for(int i=0;i<row;i++){
int A[] = new int[col];
for(int j=0;j<col;j++){
int k=i;
int temp=0;
while(k>=0){
if(matrix[k][j]=='1'){
temp++;
}
else
break;
k--;
}
A[j]=temp;
}
int temp = largestRectangleArea(A);
if(temp>max)
max=temp;
}
return max;
}
public static int largestRectangleArea(int[] heights) {
if(heights==null||heights.length<1)return 0;
int n=heights.length;
if(n==1)return heights[0];
int max=0;
Stack<Integer> st = new Stack<Integer>();
st.push(heights[0]);
int i=1;
while(i<n){
if(heights[i]>=st.peek()){
st.push(heights[i]);
}
else{
int count1=1;
while(!st.isEmpty()&&st.peek()>heights[i]){
int temp=st.pop();
if(count1*temp>max){
max=count1*temp;
}
count1++;
}
while(count1-->0){
st.push(heights[i]);
}
}
i++;
}
int count1=1;
while(!st.isEmpty()){
int temp=st.pop();
if(count1*temp>max){
max=count1*temp;
}
count1++;
}
return max;
}