Problem:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
思路:
遍历二维数组中的每一个元素,如果这个元素非0,则储存其对应的左边界和右边界,乘上对应的高度,然后求max即得到最大值。
Solution (C++):
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return 0;
int m = matrix.size(), n = matrix[0].size();
vector<int> left_bound(n), right_bound(n, n-1), height(n);
int max_area = 0;
for (int i = 0; i < m; ++i) {
int cur_left = 0, cur_right = n-1;
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == '1') height[j]++;
else height[j] = 0;
}
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == '1') left_bound[j] = max(left_bound[j], cur_left);
else {left_bound[j] = 0; cur_left = j+1;}
}
for (int j = n-1; j >= 0; --j) {
if (matrix[i][j] == '1') right_bound[j] = min(right_bound[j], cur_right);
else {right_bound[j] = n-1; cur_right = j-1;}
}
for (int j = 0; j < n; ++j) {
max_area = max(max_area, (right_bound[j]-left_bound[j]+1) * height[j]);
}
}
return max_area;
}
性能:
Runtime: 16 ms Memory Usage: 10.5 MB