"Leetcode 221" maximal Square

Source: Internet
Author: User

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 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0

Return 4.

Ideas:

DP, the longest side length to reach the current (not 0) node Square[i][j] = min (square[i-1][j-1], min (Square[i-1][j], square[i][j-1]) + 1, that is, the top left 3 nodes in the lowest value of one plus 1. The code looks comfortable--!

1 classSolution {2  Public:3     intMaximalsquare (vector<vector<Char>>&matrix) {4         Const introws =matrix.size ();5         if(Rows = =0)6             return 0;7         8vector<vector<Char> >::iterator it =Matrix.begin ();9         Const intColumns = (*it). Size ();Ten          One         intSquare[rows][columns], ret =0; A          -          for(inti =0; i < rows; i++) -              for(intj =0; J < columns; J + +) theSQUARE[I][J] =0; -          -          for(inti =0; i < rows; i++){ -             if(matrix[i][0] =='1') +             { -square[i][0] =1; +RET =1; A             } at         } -      -          for(inti =0; i < columns; i++){ -             if(matrix[0][i] = ='1') -             { -square[0][i] =1; inRET =1; -             } to         } +          -          for(inti =1; i < rows; i++) the         { *              for(intj =1; J < columns; J + +) $             {Panax NotoginsengSQUARE[I][J] = matrix[i][j] = ='1'? Min (square[i-1][j], min (square[i][j-1], square[i-1][j-1])) +1:0; -                  the                 if(Square[i][j] >ret) +RET =Square[i][j]; A             } the         } +         returnRET *ret; -     } $};

"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.