您的位置:首页 > 其它

Maximal Rectangle

2015-09-08 15:21 369 查看
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:
int maximalRectangle(vector<vector<char>>& matrix) {
int m = matrix.size();
if(!m) return 0;
int n = matrix[0].size();
if(!n) return 0;
vector<int> height(n + 1, 0);
stack<int> st;
int maxArea = 0;
for(int i = 0; i < m; ++i)
{
while(!st.empty()) st.pop();
for(int j = 0; j < n; ++j) height[j] = matrix[i][j] == '0' ? 0 : height[j] + 1;
for(int j = 0; j <= n; ++j)
{
if(st.empty() || height[j] >= height[st.top()]) st.push(j);
else
{
int temp = st.top();
st.pop();
maxArea = max(maxArea, height[temp] * (st.empty() ? j : j - st.top() - 1));
j--;
}
}
}

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