Intuition:2d DP. Basic Idea:compose Square at Dp[i][j] from dp[i-1][j-1]. You need 2 facility 2D matrix:accumulated horizontal\vertical number of 1s.
classsolution{ Public: intMaximalsquare (vector<vector<Char>>&m) {size_t row=m.size (); if(Row = =0)return 0; size_t Col= m[0].size (); Vector<vector<int>> Hori (Row, vector<int> (col,0)); Vector<vector<int>> vert (Row, vector<int> (col,0)); Vector<vector<int>> dp (Row, vector<int> (col,0)); for(inti =0; i < row; i++) for(intj =0; J < Col; J + +) { intv = m[i][j]-'0'; if(J = =0) Hori[i][j] =v; Else if(v = =0) Hori[i][j] =0; ElseHORI[I][J] = hori[i][j-1] +1; } for(intj =0; J < Col; J + +) for(inti =0; i < row; i++) { intv = m[i][j]-'0'; if(i = =0) Vert[i][j] =v; Else if(v = =0) Vert[i][j] =0; ElseVERT[I][J] = vert[i-1][J] +1; } // intRET =0; for(inti =0; i < row; i++) {dp[i][0] = m[i][0] -'0'; if(dp[i][0]) ret =1; } for(intj =0; J < Col; J + +) {dp[0][J] = m[0][J]-'0'; if(dp[0][J]) ret =1; } for(inti =1; i < row; i++) for(intj =1; J < Col; J + +) { intv = m[i][j]-'0'; if(v) {intA = Dp[i-1][j-1] +1; intb =std::min (Hori[i][j], vert[i][j]); DP[I][J]=Std::min (A, b); RET=Std::max (ret, dp[i][j]); } Else{Dp[i][j]= M[i][j]-'0'; } } returnRET *ret; }};
Leetcode "Maximal Square"