Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
将二维的问题转换为一维问题 Largest Rectangle in Histogram
public class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length < 1 || matrix[0].length < 1) {
return 0;
}
int rows = matrix.length;
int cols = matrix[0].length;
int[] height = new int[cols];
int max = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == '1') {
height[j] += 1;
} else {
height[j] = 0;
}
}
max = Math.max(max, largestRectangleArea(height));
}
return max;
}
private int largestRectangleArea(int[] height) {
if (height == null || height.length < 1) {
return 0;
}
int max = 0;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < height.length; i++) {
while (!stack.isEmpty() && height[i] <= height[stack.peek()]) {
int curIndex = stack.pop();
int nowArea = 0;
if (stack.isEmpty()) {
nowArea = i * height[curIndex];
} else {
nowArea = (i - stack.peek() - 1) * height[curIndex];
}
if (nowArea > max) {
max = nowArea;
}
}
stack.push(i);
}
while (!stack.isEmpty()) {
int curIndex = stack.pop();
int nowArea = 0;
if (stack.isEmpty()) {
nowArea = (height.length) * height[curIndex];
} else {
nowArea = (height.length - stack.peek() - 1) * height[curIndex];
}
if (nowArea > max) {
max = nowArea;
}
}
return max;
}
}