Leetcode Analysis _85. Maximal Rectangle

Source: Internet
Author: User
"title"

Topic link
Given a 2D binary matrix filled with 0 "s and 1 ' s, find the largest rectangle containing only 1 's and return their area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 6 "Analysis"

Runtime

At first I think it can be a dynamic planning idea, such as:

MATRIX[I-1][J-1]–>MATRIX[I][J] or
MATRIX[I-1][J-1],MATRIX[I-1][J],MATRIX[I][J-1]–>MATRIX[I][J]

After several thoughts and practice, it seems that it is not going through
(Note: But this kind of thought is OK in 221.Maximal Square , the solving is detailed as follows: Leetcode the analysis _221. Maximal Square (graphic analysis))

Later found on a question 84. Largest Rectangle in histogram(see the solution to the details: Leetcode analysis _84. Largest Rectangle in histogram) the idea of dynamic programming to solve this problem
Leetcode put them together is really good hard.
is to use each line as a bottom, apply 84 of the practice, on AC

For example:
1 0 0 1 1
1 0 1 1 1
0 1 1 1 0
0 1 1 1 1
First line: heights[]: 1 0 0 1 1
Second line: heights[]: 2 0 1 2 2
Third line: heights[]: 0 1 2 3 0
Line Fourth: heights[]: 0 2 3 4 1

Class Solution {public:int maximalrectangle (vector<vector<char>>& matrix) {int row = Matrix
        . Size ();   
        if (row = = 0) return 0;
        int col = matrix[0].size ();
        vector< int > Heights (col, 0);
        int max_area = 0;
        Heights.push_back (0);
            for (int i = 0; i < row i + +) {int top = 0, cur = 0;
            Vector<int> Temp (heights.size (), 0);
            Temp[top] =-1; for (int j = 0; J < Heights.size (); j + +) {if (J!= heights.size ()) heights[j] = matrix[i][j] = = ' 1 ' ?
                1 + heights[j]: 0; while (Top > 0 && heights[temp[top]] >= heights[j]) {cur= (J-temp[top-1]-1) * H
                    eights[Temp[top]];
                    top--;
                Max_area = max (Max_area, cur);
            } Temp[++top] = j;
    } return Max_area; }
};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.