1、给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
//求矩阵最大面积
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
int maxAreaV2(std::vector<int> arr) {
arr.push_back(0);
int n = arr.size();
int ans = 0;
std::stack<int> st;
for (int i = 0; i < n; ++i) {
while (!st.empty() && arr[st.top()] > arr[i]) {
int top = st.top();
int h = arr[top];
int w = i - top;
ans = std::max(ans, h * w);
st.pop();
if (st.empty()) {
break;
}
}
st.push(i);
}
return ans;
}
int getMaxArea(std::vector< std::vector<char> >& arr) {
int ans = 0;
int rows = arr.size();
int cols = arr[0].size();
std::vector<int> matrix(cols, 0);
for (int row_idx=0; row_idx < rows; row_idx++) {
for (int col_idx =0; col_idx < cols; col_idx++) {
if (arr[row_idx][col_idx] == '1'){
matrix[col_idx] = (row_idx == 0 ? 0 : matrix[col_idx]) + 1;
} else {
matrix[col_idx] = 0;
}
}
for (auto x : matrix) {
printf("%d\t", x);
}
printf("\n");
ans = std::max(ans, maxAreaV2(matrix));
}
return ans;
}
int main() {
std::vector<std::vector<char>> arr{ {'1', '0', '1', '1', '0'}, \
{'1', '0', '1', '1', '1'}, \
{'1', '1', '1', '1', '1'},\
{'1', '0', '1', '1', '0'} \
};
int res = getMaxArea(arr);
printf("%d\n", res);
return 1;
}