Maximal Rectangle

描述

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

分析

代码

  1. // Maximal Rectangle
  2. // 时间复杂度O(n^2),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. int maximalRectangle(vector<vector<char> > &matrix) {
  6. if (matrix.empty()) 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. int left = 0, right = n;
  15. // calculate L(i, j) from left to right
  16. for (int j = 0; j < n; ++j) {
  17. if (matrix[i][j] == '1') {
  18. ++H[j];
  19. L[j] = max(L[j], left);
  20. } else {
  21. left = j+1;
  22. H[j] = 0; L[j] = 0; R[j] = n;
  23. }
  24. }
  25. // calculate R(i, j) from right to left
  26. for (int j = n-1; j >= 0; --j) {
  27. if (matrix[i][j] == '1') {
  28. R[j] = min(R[j], right);
  29. ret = max(ret, H[j]*(R[j]-L[j]));
  30. } else {
  31. right = j;
  32. }
  33. }
  34. }
  35. return ret;
  36. }
  37. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/dp/maximal-rectangle.html