[Leetcode] 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.

Thinking of solving problems
1) Construct a sum matrix S[r ][c ] for the given M[r ][c ].  a) Copy first row and first columns as it is from m[][] to s[][]   b) for other entries, use following expressions to construct s[][]   If m[i][j ] is 1 then   S[i][j] = min (s[i][j-1], s[i-1][j], s[i-1][j-1]) + 1   Else/*if M[i][j] is 0*/  S[i][j] = 0  2) Find the M Aximum entry in S[r ][c ] 3) Using the Value and coordinates of maximum entry in s[i], print sub-matrix of m[][]  

More specific ways to solve the problem see geeksforgeeks.

Implementation code
classSolution { Public:intMaximalsquare ( vector<vector<char>>& Matrix) {if(Matrix.empty ()) {return 0; }introw = Matrix.size ();intCol = matrix[0].size (); vector<vector<int>>S (Row, vector<int>(Col,0)); for(inti =0; i < row; i++) {if(matrix[i][0] ==' 1 ') {s[i][0] =1; }        } for(inti =0; I < col; i++) {if(matrix[0][i] = =' 1 ') {s[0][i] =1; }        } for(inti =1; i < row; i++) { for(intj =1; J < Col; J + +) {if(Matrix[i][j] = =' 1 ') {S[i][j] = min (s[i-1][j], min (s[i][j-1], s[i-1][j-1])) +1; }Else{S[i][j] =0; }            }        }intwidth =0; for(inti =0; i < row; i++) { for(intj =0; J < Col;            J + +) {width = max (width, s[i][j]); }        }returnWidth * WIDTH; }};

[Leetcode] 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.