最大矩形
题目描述:
给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。提示:rows == matrix.lengthcols == matrix[0].length0 <= row, cols <= 200matrix[i][j] 为 '0' 或 '1'
示例
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]输出:6解释:最大矩形如上图所示。
class Solution {
public int maximalRectangle(char[][] matrix) {
int row = matrix.length;
if(row == 0) return 0;
int col = matrix[0].length;
// 初始化
int[][] heights = new int[row][col];
for(int i = 0 ; i<col ; i++){
for(int j = row-1 ; j>=0 ; j--){
if(matrix[j][i] == '1'){
heights[j][i] = ((j == row-1)?0:(heights[j+1][i]))+1;
}
}
}
int max = 0;
for(int i = 0 ; i<row ; i++){
// 遍历每一行
int temp = largestRectangleArea(heights[i]);
max = (max>temp)?max:temp;
}
return max;
}
private int largestRectangleArea(int[] heights) {
int len = heights.length;
if(len == 0) return 0;
if (len == 1) return heights[0];
int result = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < len; i++) {
while (!stack.empty() && heights[i] < heights[stack.peek()]) {
// 如果当前遍历下标的高度严格小于下标为栈顶的元素高度
int curHeight = heights[stack.pop()];
while (!stack.empty() && heights[stack.peek()] == curHeight) {
// 相等情况下去重
stack.pop();
}
int curWidth;
if (stack.empty()) {
curWidth = i;
} else {
curWidth = i - stack.peek() - 1;
}
result = Math.max(result, curHeight * curWidth);
}
stack.push(i);
}
// 最终处理
while (!stack.empty()) {
int curHeight = heights[stack.pop()];
while (!stack.empty() && heights[stack.peek()] == curHeight) {
stack.pop();
}
int curWidth;
if (stack.empty()) {
curWidth = len;
} else {
curWidth = len - stack.peek() - 1;
}
result = Math.max(result, curHeight * curWidth);
}
return result;
}
}
该题本质上就是单调栈的应用,读者可以首先理解完该题,再来解决此题。
首先我们需要进行预处理,即对matrix矩阵每一列的连续1的个数记录到heights矩阵中,最后以一行一行的顺序进行单调栈操作,通过每一行的最大的矩形面积更新全局最大矩形面积。读者可以试着在草稿纸上模拟,详细请看代码。