仅包含 0 和 1, 最大矩阵

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值