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