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.
思路:这道题其实是 LeetCode 84. Largest Rectangle in Histogram(java)的变形,只是这里从一维数组变成二维数组,因此,我们的策略就是逐行扫描,每一行都计算一次largest rectangle in histogram,因此我们需要用一个height[]数组来保存逐行扫描的histogram的结果,每行都调用一次largest rectangle in histogram的代码,最后maintain一个最大值即可。
class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
int row = matrix.length;
int col = matrix[0].length;
int[] height = new int[col + 1];
height[col] = 0;
int maxArea = 0;
for (int i = 0; i < row; i++) {
Stack<Integer> stack = new Stack<>();
for (int j = 0; j <= col; j++) {
if (j == col) {
height[j] = 0;
} else if (matrix[i][j] == '1') {
height[j] += 1;
} else {
height[j] = 0;
}
if (stack.isEmpty() || height[j] >= height[stack.peek()]) {
stack.push(j);
} else {
while (!stack.isEmpty() && height[j] < height[stack.peek()]) {
int temp = stack.pop(), len = 0;
if (stack.isEmpty()) len = j;
else len = j - 1 - stack.peek();
maxArea = Math.max(maxArea, height[temp] * len);
}
//注意这里不能再用j--,而要用stack.push(j),不然15行的height[j]++就要再加一次,会影响结果。
stack.push(j);
}
}
}
return maxArea;
}
}