您的位置:首页 > 其它

[LeetCode]Maximal Rectangle

2014-01-21 09:32 190 查看
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

思考:跟上一题一样,维护左右边界。参考:http://discuss.leetcode.com/questions/260/maximal-rectangle#

class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if (matrix.empty()) {
return 0;
}

int n = matrix[0].size();
vector<int> H(n);
vector<int> L(n);
vector<int> R(n, n);

int ret = 0;
for (int i = 0; i < matrix.size(); ++i) {
int left = 0, right = n;
// calculate L(i, j) from left to right
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == '1') {
++H[j];
L[j] = max(L[j], left);
}
else {
left = j+1;
H[j] = 0; L[j] = 0; R[j] = n;
}
}
// calculate R(i, j) from right to right
for (int j = n-1; j >= 0; --j) {
if (matrix[i][j] == '1') {
R[j] = min(R[j], right);
ret = max(ret, H[j]*(R[j]-L[j]));
}
else {
right = j;
}
}
}

return ret;
}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: