Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
Example:
Input:
[
[“1”,“0”,“1”,“0”,“0”],
[“1”,“0”,“1”,“1”,“1”],
[“1”,“1”,“1”,“1”,“1”],
[“1”,“0”,“0”,“1”,“0”]
]
Output: 6
给出一个二维的char数组,判断其中‘1’构成的最大矩形面积
注意两点:1,input是char类型数组,而不是int , 2.矩形
思路:
两种方法,一种是84题的拓展,一种是dp
(1) 84题的拓展
一层一层读input,把每个元素看成直方图的高度,用一个数组heights[]保存累加高度
第一行: heights={1, 0, 1, 0, 0}
第二行:heights变成{2, 0, 2, 1, 1}
即元素=0时,heights对应的元素清0, =1时heights对应元素+1
把heights看作是一个直方图,这时转化为求直方图中最大矩形面积
每一行设置完heights后,都求一次最大矩形面积
其中maxHistArea函数为求直方图最大矩阵面积函数,参照84题代码
public int maximalRectangle(char[][] matrix) {
if(matrix == null || matrix.length == 0) {
return 0;
}
int m = matrix.length;
int n = matrix[0].length;
int[] height = new int[n];
int result = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(matrix[i][j] - '0' == 0) {
height[j] = 0;
} else {
height[j] ++;
}
}
result = Math.max(result, maxHistArea(height));
}
return result;
}
public int maxHistArea(int[] hist) {
if(hist == null || hist.length == 0) {
return 0;
}
Stack<Integer> st = new Stack<>();
int area = 0;
int n = hist.length;
for(int i = 0; i < n; i++) {
while(!st.isEmpty() && hist[st.peek()] > hist[i]) {
int cur = st.pop();
area = Math.max(area, hist[cur] * (st.isEmpty() ?
i:i-st.peek()-1));
}
st.push(i);
}
while(!st.isEmpty()) {
int cur = st.pop();
area = Math.max(area, hist[cur] * (st.isEmpty() ?
n:n-st.peek()-1));
}
return area;
}