85. Maximal Rectangle

爱被打了一巴掌 2022-05-06 04:28 297阅读 0赞

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.

Input:
[
[“1”,“0”,“1”,“0”,“0”],
[“1”,“0”,“1”,“1”,“1”],
[“1”,“1”,“1”,“1”,“1”],
[“1”,“0”,“0”,“1”,“0”]
]
Output: 6

这道题目使用本是想使用动归但是苦于很难找到合适的对于子问题的划分。
介于Largest Rectangle in Histogram的启发式算法,应用于这道题目。
最终的时间复杂度为o(n*m)

  1. class Solution {
  2. public:
  3. int largestRectangleArea(vector<int>& heights) {
  4. int n = heights.size();
  5. if(n==0) return 0;
  6. if(n==1) return heights[0];
  7. int res = 0;
  8. heights.push_back(0);
  9. stack<int> s;
  10. for(int i=0;i<n+1;++i) {
  11. if(s.empty()||heights[i]>heights[s.top()])
  12. s.push(i);
  13. else {
  14. while(!s.empty()&&heights[i]<heights[s.top()]) {
  15. int t = s.top();
  16. s.pop();
  17. int h = heights[t];
  18. int w = 0;
  19. if(!s.empty())
  20. w = i - s.top() - 1;
  21. else
  22. w = i - 0;
  23. res = max(res,h*w);
  24. }
  25. s.push(i);
  26. }
  27. }
  28. return res;
  29. }
  30. int maximalRectangle(vector<vector<char>>& matrix) {
  31. int n = matrix.size();
  32. if(!n) return 0;
  33. int m = matrix[0].size();
  34. if(!m) return 0;
  35. if(n==1&&m==1) return matrix[0][0]=='1';
  36. int res = 0;
  37. vector<int> dp(m,0);
  38. for(int i=0;i<n;++i) {
  39. for(int j=0;j<m;++j) {
  40. dp[j] = (matrix[i][j]=='1')?dp[j]+1:0;
  41. }
  42. res = max(res,largestRectangleArea(dp));
  43. }
  44. return res;
  45. }
  46. };

发表评论

表情:
评论列表 (有 0 条评论,297人围观)

还没有评论,来说两句吧...

相关阅读