[LeetCode] 048: Maximal Rectangle

本文提供了一种寻找二维二进制矩阵中包含全1的最大矩形的方法,并详细展示了通过计算每行的高度数组来求解该问题的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[Problem]
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

[Solution]

class Solution {
public:
// get the size of the maximal rectangle
int maximalRectangle(int height[], int len){
if(len == 0)return 0;

// set the leftH
int leftH[len];
for(int i = 0; i < len; ++i){
if(i == 0 || height[i] > height[i-1]){
leftH[i] = i;
}
else{
int j = leftH[i-1];
while(true){
if(j != leftH[j]){
j = leftH[j];
}
else if(j > 0 && height[j-1] >= height[i]){
j--;
}
else{
break;
}
}
leftH[i] = j;
}
}

// set the rightH
int rightH[len];
for(int i = len-1; i >= 0; --i){
if(i == len-1 || height[i] > height[i+1]){
rightH[i] = i;
}
else{
int j = rightH[i+1];
while(true){
if(j != rightH[j]){
j = rightH[j];
}
else if(j < len-1 && height[j+1] >= height[i]){
j++;
}
else{
break;
}
}
rightH[i] = j;
}
}

// get the maximal rectangle
int res = 0, area = 0;
for(int i = 0; i < len; ++i){
area = height[i] * (rightH[i] - leftH[i] + 1);
res = max(res, area);
}
return res;
}
// get the maximal rectangle in the matrix
int maximalRectangle(vector<vector<char> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// empty matrix
if(matrix.size() == 0 || matrix[0].size() == 0)return 0;

// init height
int **height = new int*[matrix.size()];
for(int i = 0; i < matrix.size(); ++i){
height[i] = new int[matrix[i].size()];
for(int j = 0; j < matrix[i].size(); ++j){
// the height is 0
if(matrix[i][j] == '0'){
height[i][j] = 0;
}
else{
// the height is the previous row's height +1
if(i > 0){
height[i][j] = height[i-1][j] + 1;
}
else{
height[i][j] = 1;
}
}
}
}

// get result
int res = 0;
for(int i = 0; i < matrix.size(); ++i){
res = max(res, maximalRectangle(height[i], matrix[i].size()));
}
return res;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值