Leetcode Maximal Rectangle

来源:互联网 发布:check windows version 编辑:程序博客网 时间:2024/05/20 13:07

这道题还是忘了怎么解了。有一个特别巧妙的方法是利用柱状图那道题的解法。对每个格子,看从当前行往上有多少连续行为‘1’,这样就构造出了柱状图那道题中的height数组,用同样的方法可以在O(n)的时间复杂度内算出来以当前行为底的最大矩形的面积,由于有n行,所以时间复杂度为O(n^2)。

#include <iostream>#include <vector>#include <stack>using namespace std;class Solution {public:int maximalRectangle(vector<vector<char> > &matrix) {if (matrix.size() == 0){return 0;}std::vector<int> height(matrix[0].size(), 0);int area, maxarea = 0, h;for (int r = 0; r < matrix.size(); ++r){stack<int> indexes;for (int c = 0; c < matrix[r].size(); ++c){if (matrix[r][c] == '0'){height[c] = 0;}else{height[c] = height[c] + 1;}if (indexes.empty() || height[c] >= height[indexes.top()]){indexes.push(c);}else{while (!indexes.empty() && height[c] < height[indexes.top()]){h = height[indexes.top()];indexes.pop();if (!indexes.empty()){area = h * (c - indexes.top() - 1);}else{area = h * c;}if (area > maxarea){maxarea = area;}}indexes.push(c);}}while (!indexes.empty()){h = height[indexes.top()];indexes.pop();if (!indexes.empty()){area = h * (matrix[r].size() - indexes.top() - 1);}else{area = h * matrix[r].size();}if (area > maxarea){maxarea = area;}}}return maxarea;}};int main(){Solution s;// 4// vector<vector<char> > matrix(3, std::vector<char>(4, '0'));// matrix[0][0] = '1';// matrix[1][1] = '1';// matrix[1][2] = '1';// matrix[2][1] = '1';// matrix[2][2] = '1';std::vector<std::vector<char> > matrix(6, std::vector<char>(5, '0'));matrix[0][1] = '1';matrix[0][2] = '1';matrix[0][4] = '1';matrix[1][0] = '1';matrix[1][1] = '1';matrix[1][3] = '1';matrix[2][1] = '1';matrix[2][2] = '1';matrix[2][3] = '1';matrix[3][0] = '1';matrix[3][1] = '1';matrix[3][2] = '1';matrix[3][3] = '1';matrix[4][0] = '1';matrix[4][1] = '1';matrix[4][2] = '1';matrix[4][3] = '1';matrix[4][4] = '1';cout<<s.maximalRectangle(matrix)<<endl;return 0;}


0 0