[LeetCode] Maximal Rectangle

简介: This link shares a nice solution with explanation using DP. You will be clear of the algorithm after running it on its suggested example: matrix = ...

This link shares a nice solution with explanation using DP. You will be clear of the algorithm after running it on its suggested example:

matrix = [
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0]];

The code is rewritten as follows.

 1 class Solution {
 2 public:
 3     int maximalRectangle(vector<vector<char>>& matrix) {
 4         if (matrix.empty()) return 0;
 5         const int m = matrix.size(), n = matrix[0].size();
 6         int *left = new int[n](), *right = new int[n](), *height = new int[n]();
 7         fill_n(right, n, n);
 8         int area = 0;
 9         for (int i = 0; i < m; i++) {
10             int l = 0, r = n;
11             for (int j = 0; j < n; j++)
12                 height[j] += matrix[i][j] == '1' ? 1 : -height[j];
13             for (int j = 0; j < n; j++) {
14                 if (matrix[i][j] == '1') left[j] = max(left[j], l);
15                 else left[j] = 0, l = j + 1;
16             }
17             for (int j = n - 1; j >= 0; j--) {
18                 if (matrix[i][j] == '1') right[j] = min(right[j], r);
19                 else right[j] = n, r = j;
20             }
21             for (int j = 0; j < n; j++)
22                 area = max(area, (right[j] - left[j]) * height[j]);
23         }
24         return area;
25     }
26 };

 

目录
相关文章
LeetCode 836. 矩形重叠 Rectangle Overlap
LeetCode 836. 矩形重叠 Rectangle Overlap
LeetCode 836. 矩形重叠 Rectangle Overlap
LeetCode 221. Maximal Square
在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。
62 0
LeetCode 221. Maximal Square
LeetCode 85. Maximal Rectangle
题意是给定一个二维的零一矩阵,1可以用来围成一些矩阵,题意要求是返回围城矩阵的面积最大值.
83 0
LeetCode 85. Maximal Rectangle
Leetcode-Hard 84. Largest Rectangle in Histogram
Leetcode-Hard 84. Largest Rectangle in Histogram
102 0
Leetcode-Hard 84. Largest Rectangle in Histogram
LeetCode之Construct the Rectangle
LeetCode之Construct the Rectangle
75 0
LeetCode 223 Rectangle Area(矩形面积)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50593348 翻译 找到在二维平面中两个相交矩形的总面积。
821 0