"Leetcode" 221. Maximal Square

Source: Internet
Author: User

Maximal Square

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

For example, given the following matrix:

1 1 1 1 11 0 0 1 0

Return 4.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

The DP thought part of this question draws on the jianchao.li.fighter.

Here's the idea: building a two-dimensional array len,len[i][j] represents the length of the largest square in the lower-right corner (I,J).

The recurrence relationship is len[i][j] = min (min (len[i-1][j], len[i][j-1]), len[i-1][j-1]) + 1;

As indicated:

The maximum square side length (I,J) is the lower right corner, depending on the surrounding three positions (I-1,j), (i,j-1), (i-1,j-1), which is exactly the minimum edge length of the three to expand 1 bits.

If the minimum side length of the three is 0, then (i,j) from the side length of 1 blocks.

classSolution { Public:    intMaximalsquare (vector<vector<Char>>&matrix) {        if(Matrix.empty () | | matrix[0].empty ())return 0; intm =matrix.size (); intn = matrix[0].size (); intMaxLen =0; Vector<vector<int> > Len (M, vector<int> (n,0)); //First Row         for(inti =0; I < n; i + +) {len[0][i] = (int) (matrix[0][i]-'0'); if(len[0][i] = =1) MaxLen=1; }        //First Col         for(inti =0; I < m; i + +) {len[i][0] = (int) (matrix[i][0]-'0'); if(len[i][0] ==1) MaxLen=1; }         for(inti =1; I < m; i + +)        {             for(intj =1; J < N; J + +)            {                if(Matrix[i][j] = ='0') Len[i][j]=0; Else{Len[i][j]= Min (min (len[i-1][J], len[i][j-1]), len[i-1][j-1]) +1; MaxLen=Max (Len[i][j], maxlen); }            }        }        returnMaxLen *MaxLen; }};

"Leetcode" 221. Maximal Square

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.