问题描述:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] Output: 6
解题思路:
这给我们一个二维矩阵要我们求出其中可以构成的最大矩形。
可以把它降维度到一维:即可变成求histgram可以构成的最大矩形。
每一行和上面的行形成一个histogram。
如图所示(以所给例子的最后一行为例):
一定要为连续的不为0的才能累成柱状图!
代码:
class Solution { public: int maximalRectangle(vector<vector<char>>& matrix) { if(matrix.empty()) return 0; vector<int> height(matrix[0].size(), 0); height.push_back(0); int m = 0; for(int i = 0; i < matrix.size(); i++){ stack<int> stk; for(int j = 0; j < matrix[0].size(); j++){ int num = matrix[i][j] - '0'; if(num != 0){ height[j] += num; }else{ height[j] = 0; } } for(int j = 0; j <= matrix[0].size(); j++){ while(!stk.empty() && height[j] <= height[stk.top()]){ int cur = stk.top(); stk.pop(); m = max(m, height[cur] * (stk.empty() ? j : (j - stk.top() - 1))); } stk.push(j); } } return m; } };