[leetcode] 85. Maximal Rectangle

古城微笑少年丶 2022-06-13 03:27 308阅读 0赞

85. Maximal Rectangle
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
return 6.

给定一个二维矩阵,里面的元素分别为1或者0,找出一个矩阵,元素都是1,并返回该矩阵的面积。
例如,给定矩阵如下:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
则返回矩阵的面积为6。

解题思路
这道题的难度系数标记为Hard。因为我们要找的是一个全是1的二维矩阵,也就是说该矩阵是以某个元素开始,然后以该元素有起点分别向右和向下延伸,形成一个矩阵。
本题可通过动态规划进行求解。

代码实现如下:

  1. class Solution {
  2. // 时间复杂度 O(n^2),空间复杂度 O(n)
  3. public:
  4. int maximalRectangle(vector<vector<char>>& matrix) {
  5. if(matrix.empty())
  6. return 0;
  7. const int m = matrix.size();
  8. const int n = matrix[0].size();
  9. vector<int> H(n, 0);
  10. vector<int> L(n, 0);
  11. vector<int> R(n, n);
  12. int ret = 0;
  13. for(int i = 0; i < m; ++i)
  14. {
  15. int left = 0, right = n;
  16. //calculate L(i,j) from left to right
  17. for(int j = 0; j < n; ++j)
  18. {
  19. if(matrix[i][j] == '1')
  20. {
  21. ++H[j];
  22. L[j] = max(L[j], left);
  23. }
  24. else
  25. {
  26. left = j+1;
  27. H[j] = 0;
  28. L[j] = 0;
  29. R[j] = n;
  30. }
  31. }
  32. //calculate R(i,j) from right to left
  33. for(int j = n-1; j >= 0; --j)
  34. {
  35. if(matrix[i][j] == '1')
  36. {
  37. R[j] = min(R[j], right);
  38. ret = max(ret, H[j]*(R[j] - L[j]));
  39. }
  40. else
  41. {
  42. right = j;
  43. }
  44. }
  45. }
  46. return ret;
  47. }
  48. };

发表评论

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

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

相关阅读