Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
A clever question. For a 0-1 matrix, each row and above can be considered as a histogram (as shown in). Using largest rectangle in histogram, you can search the rectangle with the largest area in the histogram of this row and above at O (n) time, and perform this operation on each row of the matrix in sequence, then you can) time to search for the largest rectangle.
To convert the original matrix to a histogram matrix, use the transfer matrix to store the converted histogram.
transfer[0][j] = matrix[0][j] - ‘0‘;transfer[i][j] = (matrix[i][j] == ‘0‘ ? 0: transfer[i-1][j] + 1); (i >= 1)
The Code is as follows:
1 public class Solution { 2 public int largestRectangleArea(int[] height) { 3 if(height == null || height.length == 0) 4 return 0; 5 Stack<Integer> index = new Stack<Integer>(); 6 int totalMax = 0; 7 ArrayList<Integer> newHeight = new ArrayList<Integer>(); 8 for(int i:height) newHeight.add(i); 9 newHeight.add(0);10 11 12 for(int i = 0;i < newHeight.size();i++){13 if(index.isEmpty() || newHeight.get(i) >= newHeight.get(index.peek()))14 index.push(i);15 else{16 int top = index.pop();17 totalMax = Math.max(totalMax,newHeight.get(top) * (index.isEmpty()?i:i-index.peek()-1));18 i--;19 }20 }21 22 return totalMax;23 }24 public int maximalRectangle(char[][] matrix) {25 if(matrix == null || matrix.length == 0)26 return 0;27 int m = matrix.length;28 int n = matrix[0].length;29 int totalMax = 0;30 int[][] transfer = new int[m][n];31 32 //transform matrix to histogram in a new matrix33 for(int i = 0;i < n;i++)34 transfer[0][i] = matrix[0][i]- ‘0‘;35 for(int i = 1;i < m;i++){36 for(int j = 0;j < n;j++){37 if(matrix[i][j] == ‘0‘ )38 transfer[i][j] = 0;39 else {40 transfer[i][j] = transfer[i-1][j] + 1; 41 }42 }43 }44 45 //Using histogram to find the biggest rectangle46 for(int i = 0;i < m;i++){47 totalMax = Math.max(totalMax, largestRectangleArea(transfer[i]));48 }49 50 return totalMax;51 }52 }