[LintCode] Maximal Square 最大正方形

时间:2023-11-14 15:23:44

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.

Have you met this question in a real interview?
Example

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.

LeetCode上的原题,请参见我之前的博客Maximal Square

解法一:

class Solution {
public:
/**
* @param matrix: a matrix of 0 and 1
* @return: an integer
*/
int maxSquare(vector<vector<int> > &matrix) {
if (matrix.empty() || matrix[].empty()) return ;
int m = matrix.size(), n = matrix[].size(), res = ;
vector<vector<int>> sum = matrix;
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
int t = sum[i][j];
if (i > ) t += sum[i - ][j];
if (j > ) t += sum[i][j - ];
if (i > && j > ) t -= sum[i - ][j - ];
sum[i][j] = t;
int cnt = ;
for (int k = min(i, j); k >= ; --k) {
int d = sum[i][j];
if (i - cnt >= ) d -= sum[i - cnt][j];
if (j - cnt >= ) d -= sum[i][j - cnt];
if (i - cnt >= && j - cnt >= ) d += sum[i - cnt][j - cnt];
if (d == cnt * cnt) res = max(res, d);
++cnt;
}
}
}
return res;
}
};