Leetcode: maximal rectangle-1 submatrix

Source: Internet
Author: User

Maximal rectangle

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing all ones and return its area.

Solution Analysis:

The maximum rectangle area can be obtained in O (n) time.

If we regard each row as the X coordinate, the height is the number of 1 starting from that row.

Using the maximum rectangular area method, we can find the maximum rectangular area of each row in the O (n2) time.

Class solution {public: int maximalrectangle (vector <char> & matrix) {int nrow = matrix. size (); If (nrow = 0) return 0; int ncol = matrix. at (0 ). size (); STD: vector <int> TMP (ncol, 0); int result = 0; For (INT I = 0; I <nrow; ++ I) {// calculate the maximum rectangular area that can be formed for (Int J = 0; j <ncol; ++ J) {If (matrix. at (I ). at (j) = '0') {TMP. at (j) = 0;} else {TMP. at (j) ++; // calculate the cumulative height of the current column of the current row (number of 1)} int Area = Largestrectanglearea (TMP); Result = STD: max (result, area);} return result;} // maximum rectangular area int largestrectanglearea (STD :: vector <int> & height) {If (height. size () = 0) return 0; height. push_back (-1); STD: Stack <int> STK; int result = 0; For (INT I = 0; I 

 

Leetcode: maximal rectangle-1 submatrix

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.