1. 概述

给定一个仅包含 01 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例:
image.png
输入:matrix = [
[“1”,”0”,”1”,”0”,”0”],
[“1”,”0”,”1”,”1”,”1”],
[“1”,”1”,”1”,”1”,”1”],
[“1”,”0”,”0”,”1”,”0”]
]
输出:6
解释:最大矩形如上图所示。

1.1 思路

1.1.1 递增栈

  1. 计算出每行向上累积的高度
  2. 对每行的高度做一次取最大矩形(leetcode-84题:柱状图通过单调递增栈找到最大矩形)
  3. 对比行柱状图的最大矩形,取出最大矩形

    2. 解题

    ```php <?php

class Solution { /**

  1. * @param Integer[][] $matrix
  2. * @return Integer
  3. */
  4. public function maximalRectangle($matrix)
  5. {
  6. $max = $this->largestRectangleArea($matrix[0]);
  7. for ($i = 1; $i < count($matrix); $i++) {
  8. for ($j = 0; $j < count($matrix[0]); $j++) {
  9. ($matrix[$i][$j]) && $matrix[$i][$j] += $matrix[$i - 1][$j];
  10. }
  11. $max = max($max, $this->largestRectangleArea($matrix[$i]));
  12. }
  13. return $max;
  14. }
  15. /**
  16. * leetcode-84 柱状图中最大的矩形
  17. * @param Integer[] $heights
  18. * @return Integer
  19. */
  20. private function largestRectangleArea($heights)
  21. {
  22. if (!$heights) return 0;
  23. $n = count($heights);
  24. $increaseStack = new SplStack();
  25. // 通过递增栈来确定 左边界
  26. $rightMargin = $leftMargin = [];
  27. for ($i = 0; $i < $n; $i++) {
  28. while (!$increaseStack->isEmpty() && $heights[$increaseStack->top()] >= $heights[$i]) {
  29. $increaseStack->pop();
  30. }
  31. $leftMargin[$i] = $increaseStack->isEmpty() ? -1 : $increaseStack->top();
  32. $increaseStack->push($i);
  33. }
  34. // 通过递增栈来确定 右边界
  35. $reduceStack = new SplStack();
  36. for ($j = $n - 1; $j >= 0; $j--) {
  37. while (!$reduceStack->isEmpty() && $heights[$reduceStack->top()] >= $heights[$j]) {
  38. $reduceStack->pop();
  39. }
  40. $rightMargin[$j] = $reduceStack->isEmpty() ? $n : $reduceStack->top();
  41. $reduceStack->push($j);
  42. }
  43. // 计算最大矩形
  44. $answer = 0;
  45. for ($i = 0; $i < $n; $i++) {
  46. $answer = max($answer, ($rightMargin[$i] - $leftMargin[$i] - 1) * $heights[$i]);
  47. }
  48. return $answer;
  49. }

}

$matrix = [ [“1”, “0”, “1”, “0”, “0”], [“1”, “0”, “1”, “1”, “1”], [“1”, “1”, “1”, “1”, “1”], [“1”, “0”, “0”, “1”, “0”] ]; $cls = new Solution(); $ret = $cls->maximalRectangle($matrix); echo $ret; ```