Intuition: 2D DP. Basic idea: compose square at dp[i][j] from dp[i-1][j-1]. You need 2 facility 2D matrix: accumulated horizontalvertical number of 1s.
class Solution { public: int maximalSquare(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 (int i = 0; i < row; i++) for (int j = 0; j < col; j++) { int v = m[i][j] - '0'; if (j == 0) hori[i][j] = v; else if (v == 0) hori[i][j] = 0; else hori[i][j] = hori[i][j - 1] + 1; } for (int j = 0; j < col; j++) for (int i = 0; i < row; i++) { int v = m[i][j] - '0'; if (i == 0) vert[i][j] = v; else if (v == 0) vert[i][j] = 0; else vert[i][j] = vert[i - 1][j] + 1; } // int ret = 0; for (int i = 0; i < row; i++) { dp[i][0] = m[i][0] - '0'; if (dp[i][0]) ret = 1; } for (int j = 0; j < col; j++) { dp[0][j] = m[0][j] - '0'; if (dp[0][j]) ret = 1; } for (int i = 1; i < row; i++) for (int j = 1; j < col; j++) { int v = m[i][j] - '0'; if (v) { int a = dp[i - 1][j - 1] + 1; int b = 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'; } } return ret * ret; } };