码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Maximal Rectangle"

时间:2014-08-24 09:08:32      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   div   log   amp   

My intuition is flood-fill the BFS solution, which is O(n^4); and then I figured out a DP solution which is O(n^4)..

So I googled some hints: it can be built upon another LeetCode problem: Largest Rectangle in Histogram. With proper pre-calculation, we can make a O(n^3) solution. 

Check out my code which completely builds upon my code to "Largest Rectangle in Histogram":

class Solution {
public:
    //
    struct Rec
    {
        Rec() : minH(0), area(0) {};
        Rec(int h, int a) : minH(h), area(a) {};
        int minH;
        int area;
    };
    int largestRectangleArea(vector<int> &height) {
        size_t cnt = height.size();

        int max = std::numeric_limits<int>::min();
        vector<Rec> dp;
        dp.resize(cnt);
        for (int i = 0; i < cnt; i++)
        {
            dp[i].minH = height[i];
            dp[i].area = height[i];
            max = std::max(max, dp[i].area);
        }

        //    Bottom-Up DP
        for (int ilen = 2; ilen <= cnt; ilen++)
        for (int i = 0; i <= cnt - ilen; i++)
        {
            int newH = height[i + ilen - 1];
            int opH = std::min(dp[i].minH, newH);
            int newA = opH * ilen;
            dp[i].minH = opH;
            dp[i].area = newA;
            max = std::max(max, newA);
        }
        return max;
    }
    //////////////
    int maximalRectangle(vector<vector<char> > &matrix) {
        int h = matrix.size();
        if (h == 0) return 0;
        int w = matrix[0].size();
        if (w == 0) return 0;

        vector<vector<int>> pre;
        pre.resize(h);
        for (int i = 0; i < h; i++)
        {
            pre[i].resize(w);
            std::fill(pre[i].begin(), pre[i].end(), 0);
        }

        //    Pre-mark
        for (int i = 0; i < h; i++)
        for (int j = 0; j < w; j++)
        {
            if (matrix[i][j] == 1)
            {
                if (j == 0) pre[i][j] = 1;
                else        pre[i][j] = pre[i][j - 1] + 1;
            }
        }

        //
        int max = 0;
        for (int i = 0; i < h; i ++)
        for (int j = 0; j < w; j ++)
        {
            if (matrix[i][j] == 1)
            {
                vector<int> heights;
                for (int k = i; k < h; k++)
                {
                    if (pre[k][j] == 0) break;
                    heights.push_back(pre[k][j]);
                }
                int currmax = largestRectangleArea(heights);
                max = std::max(max, currmax);
            }
        }
        return max;
    }
};

LeetCode "Maximal Rectangle"

标签:style   blog   color   io   for   ar   div   log   amp   

原文地址:http://www.cnblogs.com/tonix/p/3932463.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!