LeetCode解题 85:Maximal Rectangle
Problem 85: Maximal Rectangle [Hard]
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
来源:LeetCode
解题思路
本题需要沿用题解84:Largest Rectangle in Histogram的思想,相当于是对84题的二维扩展。
一个二维矩阵中的最大的全1面积,可以分解为对每一行求一次Largest Rectangle in Histogram,最后对m行结果取最大值。其中每行的histogram是该行的每一列往上能够延伸的最高全1高度。
具体过程:
- 首先遍历数组,对当前行i求取一个hist,求取公式为:
h i s t [ j ] = ( h i s t [ j ] + 1 ) ∗ m a t r i x [ i ] [ j ] , j ∈ [ 0 , n − 1 ] hist[j] = (hist[j] + 1) * matrix[i][j], j\in [0, n-1] hist[j]=(hist[j]+1)∗matrix[i][j],j∈[0,n−1]
意义是对上一行的hist[j]累计1,若当前值matrix[i][j]是0时则清零。其中n为数组的列数。 - 然后对i行的hist求Largest Rectangle in Histogram,这里使用栈的方法,具体过程见题解84:Largest Rectangle in Histogram.
- 使用返回的area更新最大面积maxArea。
整个算法遍历了m行,每行使用一次Largest Rectangle in Histogram计算复杂度为 O ( n ) O(n) O(n),因此最终的时间复杂度为 O ( m n ) O(mn) O(mn)。
Solution (Java)
class Solution {
int m, n;
public int maximalRectangle(char[][] matrix) {
m = matrix.length;
if(m == 0) return 0;
n = matrix[0].length;
int[] hist = new int[n];
int area, maxArea = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
hist[j] = (hist[j] + 1) * Integer.parseInt(String.valueOf(matrix[i][j]));
}
area = largestRect(hist);
maxArea = Math.max(maxArea, area);
}
return maxArea;
}
private int largestRect(int[] hist){
Stack<Integer> sk = new Stack<Integer>();
sk.push(-1);
sk.push(0);
int area, max = 0;
for(int i = 1; i < n; i++){
while(i < n && hist[i] >= hist[sk.peek()]){
sk.push(i);
i++;
}
if(i == n) break;
while(sk.peek() != -1 && hist[i] <= hist[sk.peek()]){
area = hist[sk.pop()] * (i - sk.peek() - 1);
max = Math.max(max, area);
}
sk.push(i);
}
while(sk.peek() != -1){
area = hist[sk.pop()] * (n - sk.peek() - 1);
max = Math.max(max, area);
}
return max;
}
}