Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
说明:参考LeetCode-Largest Rectangle in Histogram(JAVA)
针对二维数组的每一行,生成直方图,求出该直方图中的最大矩形。
class Solution {
public int maximalRectangle(char[][] matrix) {
int n = matrix.length;
if(n < 1) {
return 0;
}
int m = matrix[0].length;
if(m < 1) {
return 0;
}
int[] h = new int[m + 1];
Stack<Integer> sts = new Stack<Integer>();
int area = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(matrix[i][j] == '0') {
h[j] = 0;
} else {
h[j] += 1;
}
while(!sts.isEmpty() && h[sts.peek()] > h[j]){
int t = sts.pop();
area = Math.max(area, h[t] * (sts.isEmpty() ? j : j - sts.peek() - 1));
}
sts.push(j);
}
while(!sts.isEmpty()) {
int t = sts.pop();
area = Math.max(area, h[t] * (sts.isEmpty() ? m : m - sts.peek() - 1));
}
}
return area;
}
}