Largest Rectangle 的follow up
Problem
Given a 2D boolean matrix filled with False and True, find the largest rectangle containing all True and return its area.
Example
Given a matrix:
[
[1, 1, 0, 0, 1],
[0, 1, 0, 0, 1],
[0, 0, 1, 1, 1],
[0, 0, 1, 1, 1],
[0, 0, 0, 0, 1]
]
return 6.
思路
- 将每一行都当作求largest rectangle
public int maximalRectangle(boolean[][] matrix) {
int m = matrix.length;
int n = m == 0 ? 0 : matrix[0].length;
int[][] height = new int[m][n + 1];
int maxArea = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (! matrix[i][j]) {
height[i][j] = 0;
} else {
height[i][j] = i == 0 ? 1 : height[i - 1][j] + 1;
}
}
}
for (int i = 0; i < m; i++) {
int area = maxAreaInHist(height[i]);
if (area > maxArea) {
maxArea = area;
}
}
return maxArea;
}