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