[LeetCode 85] largest rectangle

Topic Link

【answer】


All "1" rectangle into m classes.
Rectangular j-th class. Close to the border with his right column j.
Well.
We set f [i] [j] represents the (i, j) up to this point is left "1" can be extended by how many object
so rectangle for the j-th class.
We will find. Seeking to put into question a histogram sideways.
And then let you where to find the largest rectangular area. And require close to the bottom surface (ie column j)
The question then caught into this question up.
Make a O (N) can be solved monotonic queue.
Therefore, the overall complexity is O (N ^ 2) a.

[Code]

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if (matrix.empty()) return 0;
        if (matrix[0].empty()) return 0;
        int n = matrix.size();
        int m = matrix[0].size();
        int f[1005][1005];
        memset(f,0,sizeof(f));
        for (int i = 0;i < n;i++)
            for (int j = 0;j < m;j++){
                if (matrix[i][j]=='1'){
                    f[i+1][j+1] = f[i+1][j]+1;
                }
            }
        int h[1005],sta[1005];
        memset(h,0,sizeof(h));memset(sta,0,sizeof(sta));
        int top;
        int ma = 0;
        for (int j = 1;j <= m;j++){
            for (int i = 1;i <= n;i++){
                h[i] = f[i][j];
            }
            top = 1;
            sta[1] = 0;
            for (int i = 1;i <= n;i++){
                while (top!=1 && h[sta[top]]>h[i]){
                    ma = max(ma,h[sta[top]]*(i-1-sta[top-1]));
                    top--;
                }
                sta[++top] = i;
            }
            while (top>1){
                ma = max(ma,h[sta[top]]*(n-sta[top-1]));
                top--;
            }
        }
        return ma;
    }
};

Guess you like

Origin www.cnblogs.com/AWCXV/p/11944514.html