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 0Return 6.
基于84. Largest Rectangle in Histogram,对于每一行求最大的rectangle,可以得到整个矩阵中最大的矩形面积。代码如下:
public class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0) {
return 0;
}
int m = matrix.length, n = matrix[0].length, max = 0;
for (int i = 0; i < m; i ++) {
Stack<Integer> stack = new Stack<Integer>();
int[] heights = new int[n + 1];
for (int j = 0; j <= n; j ++) {
int cur = 0;
if (j < n) {
int k = i;
while (k < m && matrix[k][j] == '1') {
cur ++;
k ++;
}
}
heights[j] = cur;
while (!stack.isEmpty() && cur <= heights[stack.peek()]) {
int h = heights[stack.pop()];
int w = stack.isEmpty()? j: j - stack.peek() - 1;
max = Math.max(max, h * w);
}
stack.push(j);
}
}
return max;
}
}