zoukankan      html  css  js  c++  java
  • [LintCode] Maximal Rectangle 最大矩形

    Given a 2D boolean matrix filled with False and True, find the largest rectangle containing all True and return its area.

    Example
    Given a matrix:

    [
    [1, 1, 0, 0, 1],
    [0, 1, 0, 0, 1],
    [0, 0, 1, 1, 1],
    [0, 0, 1, 1, 1],
    [0, 0, 0, 0, 1]
    ]
    return 6.

    LeetCode上的原题,请参见我之前的博客Maximal Rectangle

    解法一:

    class Solution {
    public:
        /**
         * @param matrix a boolean 2D matrix
         * @return an integer
         */
        int maximalRectangle(vector<vector<bool> > &matrix) {
            if (matrix.empty() || matrix[0].empty()) return 0;
            int res = 0, m = matrix.size(), n = matrix[0].size();
            vector<int> h(n + 1, 0);
            for (int i = 0; i < m; ++i) {
                stack<int> s;
                for (int j = 0; j < n + 1; ++j) {
                    if (j < n) {
                        if (matrix[i][j]) ++h[j];
                        else h[j] = 0;
                    }
                    while (!s.empty() && h[s.top()] >= h[j]) {
                        int cur = s.top(); s.pop();
                        res = max(res, h[cur] * (s.empty() ? j : (j - s.top() - 1)));
                    }
                    s.push(j);
                }
            }
            return res;
        }
    };

    解法二:

    class Solution {
    public:
        /**
         * @param matrix a boolean 2D matrix
         * @return an integer
         */
        int maximalRectangle(vector<vector<bool> > &matrix) {
            if (matrix.empty() || matrix[0].empty()) return 0;
            int res = 0, m = matrix.size(), n = matrix[0].size();
            vector<int> h(n, 0), left(n, 0), right(n, n);
            for (int i = 0; i < m; ++i) {
                int cur_left = 0, cur_right = n;
                for (int j = 0; j < n; ++j) {
                    h[j] = matrix[i][j] ? h[j] + 1 : 0;
                }
                for (int j = 0; j < n; ++j) {
                    if (matrix[i][j]) left[j] = max(left[j], cur_left);
                    else {left[j] = 0; cur_left = j + 1;}
                }
                for (int j = n - 1; j >= 0; --j) {
                    if (matrix[i][j]) right[j] = min(right[j], cur_right);
                    else {right[j] = n; cur_right = j;}
                }
                for (int j = 0; j < n; ++j) {
                    res = max(res, (right[j] - left[j]) * h[j]);
                }
            }
            return res;
        }
    };
  • 相关阅读:
    OpenGL 五
    OpenGL 四
    对UICollectionView的学习
    KVO的简单用法
    css在各浏览器中的兼容问题
    iOS学习笔记---网络请求
    UI学习笔记---第十六天XML JSON解析
    ui学习笔记---第十五天数据库
    UI学习笔记---第十四天数据持久化
    UI学习笔记---第十三天可视化设计 XIB, StoryBoard
  • 原文地址:https://www.cnblogs.com/grandyang/p/5496687.html
Copyright © 2011-2022 走看看