[Leetcode] 221 Maximal Square (Daquan 1 Square & Dynamic Planning)
When we determine the largest square in the lower right corner of a square, the top three points, left and top left, must be the bottom right corner of a square, otherwise, the largest square in the lower right corner is itself. This is a qualitative judgment. What is the maximum side length of a square? We know that this point is the maximum side length of the square in the lower right corner. It is at most 1 longer than the top side of the square in the lower right corner, and the top left side is 1 longer than the side of the square in the lower right corner, the left side and the top left side have the same size as the lower right corner of the square. In this way, a larger square can be formed by adding the point. However, if the size of the square in the lower right corner is different from that in the upper left and upper left, a corner is missing, at this time, we can only add 1 to the side length of the smallest square in the three squares. Assume that dpi indicates the maximum side length of a square in the lower right corner of I and j
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
Of course, if this point is 0 in the original matrix, then dp [I] is definitely 0.
class Solution {public: int maximalSquare(vector
>& matrix) { if (matrix.empty() || matrix[0].empty()) return 0; int M = matrix.size(), N = matrix[0].size(), res = 0; vector
> dp(M, vector
(N, 0)); for (int i = 0; i < M; ++i) if (matrix[i][0] == '1') { dp[i][0] = 1; res = 1; } for (int j = 0; j < N; ++j) if (matrix[0][j] == '1') { dp[0][j] = 1; res = 1; } for (int i = 1; i < M; ++i) { for (int j = 1; j < N; ++j) { if (matrix[i][j] == '1') dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1; res = max(res, dp[i][j]); } } return res * res; }};