[LeetCode] Maximal Rectangle

来源:互联网 发布:音频测试软件 编辑:程序博客网 时间:2024/06/07 18:44
[Problem]
Given a 2D binary matrix filled with 0's and 1's, find the largestrectangle containing all ones and return its area.

[Analysis]

和 Largest Rectangle in Histogram 的方法比较相似,对于矩阵的每一个点,确定该点能够向上达到的最大高度,然后按照 Largest Rectangle inHistogram 的方法,确定每个点上能够达到的最大矩形,最后选择最大的。

[Solution]

class Solution {
public:
// Definition for Grid
struct Grid{
int left, right, top, height;
int area;
Grid(int _left, int _right, int _top, int _height, int _area) : left(_left), right(_right), top(_top), height(_height), area(_area) {}
};

// maximal rectangle
int maximalRectangle(vector<vector<char> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// get number of rows
int m = matrix.size();
if(m == 0){
return 0;
}

// get number of columns
int n = matrix[0].size();

// init mark
vector<vector<Grid> > mark;
for(int i = 0; i < m; ++i){
vector<Grid> row;
for(int j = 0; j < n; ++j){
row.push_back(Grid(-1, -1, -1, 0, 0));
}
mark.push_back(row);
}

// set top
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(matrix[i][j] == '1'){
if(i > 0 && matrix[i-1][j] == '1'){
mark[i][j].top = mark[i-1][j].top;
mark[i][j].height = i - mark[i][j].top + 1;
}
else{
mark[i][j].top = i;
mark[i][j].height = 1;
}
}
}
}

// set left
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(matrix[i][j] == '1'){
mark[i][j].left = j;
while(mark[i][j].left >= 1 && mark[i][mark[i][j].left - 1].height >= mark[i][j].height){
mark[i][j].left = mark[i][mark[i][j].left - 1].left;
}
}
}
}

// set right
for(int i = 0; i < m; ++i){
for(int j = n-1; j >= 0; --j){
if(matrix[i][j] == '1'){
mark[i][j].right = j;
while(mark[i][j].right <= n-2 && mark[i][mark[i][j].right + 1].height >= mark[i][j].height){
mark[i][j].right = mark[i][mark[i][j].right + 1].right;
}
}
}
}

// set area
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(matrix[i][j] == '1'){
mark[i][j].area = (mark[i][j].right - mark[i][j].left + 1) * mark[i][j].height;
}
}
}

// get result
int res = 0;
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
res = max(res, mark[i][j].area);
}
}
return res;
}
};


 说明:版权所有,转载请注明出处。Coder007的博客