classSolution { public: intmaximalSquare(vector<vector<char> > &matrix) { int i, j, k, m = matrix.size(), n = matrix[0].size(); // dp[i][j] represents the size of the all-ones square with matrix[i][j] as the bottom-right corner vector<vector<int> > dp(m, vector<int>(n, 0)); int max_len = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (matrix[i][j] == '1') { dp[i][j] = 1; max_len = 1; } } }
#include<vector> #include<algorithm> using std::vector;
classSolution { public: intmaximalSquare(vector<vector<char> > &matrix) { int i, j, m = matrix.size(), n = matrix[0].size(); // dp[i][j] represents the size of the all-ones square with matrix[i][j] as the bottom-right corner vector<vector<int> > dp(m, vector<int>(n, 0)); int max_len = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (matrix[i][j] == '1') { dp[i][j] = 1; max_len = 1; } } }
bool only1; for (i = 1; i < m; i++) { for (j = 1; j < n; j++) { if (dp[i][j] == 1) { dp[i][j] = std::min({ dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1] }) + 1; max_len = std::max(dp[i][j], max_len); } } } return max_len * max_len; } };