Description:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
Solution:
This problem is very close to the last problem: largest rectangle in histogram. And all we have to do here is to try to convert this 0 and 1 2D matrix to a n height arrays. Then for each array, we can calculate a max rectangle area.
import java.io.*;
import java.util.*;
class Solution {
public static void main(String[] args){
Solution s = new Solution();
int arr[]={1,2,3};
System.out.println(s.largestRectangleArea(arr));
}
public int largestRectangleArea(int[] height) {
if(height==null)
return 0;
int n = height.length;
int h[] = new int[n+1];
h = Arrays.copyOf(height, n+1);
int max=0;
Stack<Integer> stack = new Stack<Integer>();
int i =0;
while(i<=n){
if(stack.isEmpty()||h[stack.peek()]<h[i]){
stack.push(i);
i++;
}else{
int t = stack.pop();
int ta;
if (stack.isEmpty())
ta = i * h[t];
else
ta = (i - stack.peek() - 1) * h[t];
max = Math.max(max, ta);
}
}
return max;
}
public int maximalRectangle(char[][] matrix) {
if(matrix==null||matrix.length==0)
return 0;
int n = matrix.length;
int m = matrix[0].length;
int height[] = new int[m];
int max_area = 0;
for (int i=0;i<n;i++){
for (int j=0;j<m;j++)
if(matrix[i][j]=='0')
height[j] = 0;
else
height[j] += 1;
max_area = Math.max(max_area, largestRectangleArea(height));
}
return max_area;
}
}