Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
public class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix==null || matrix.length==0 || matrix[0].length==0) {
return 0;
}
int m = matrix.length;
int n = matrix[0].length;
int max = 0;
int[] height = new int[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '0') {
height[j] = 0;
} else {
height[j] += 1;
}
}
max = Math.max(largestRectangleArea(height), max);
}
return max;
}
public int largestRectangleArea(int[] height) {
Stack<Integer> stack = new Stack<Integer>();
int i = 0;
int maxArea = 0;
int[] tmp = Arrays.copyOf(height, height.length+1);
while (i < tmp.length) {
if (stack.isEmpty() || tmp[stack.peek()] <= tmp[i]) {
stack.push(i++);
} else {
int t = stack.pop();
maxArea = Math.max(maxArea, tmp[t]*(stack.isEmpty() ? i: (i-stack.peek()-1)));
}
}
return maxArea;
}
}
本文介绍了一种求解二维二进制矩阵中全由1构成的最大矩形面积的方法。通过构建高度数组并利用栈来高效计算每个子数组的最大矩形面积,最终得出整个矩阵中的最大矩形面积。
919

被折叠的 条评论
为什么被折叠?



