前缀和预处理
/*
* @lc app=leetcode id=1139 lang=cpp
*
* [1139] Largest 1-Bordered Square
*/
// @lc code=start
class Solution {
public:
int largest1BorderedSquare(vector<vector<int>>& grid) {
int N = grid.size();
int M = grid[0].size();
// init
vector<vector<int>> Usum(N+1, vector<int>(M+1, 0));
vector<vector<int>> Lsum(N+1, vector<int>(M+1, 0));
for(int i=1;i<=N;i++){
for(int j=1;j<=M;j++){
Usum[i][j] = Usum[i-1][j] + grid[i-1][j-1];
Lsum[i][j] = Lsum[i][j-1] + grid[i-1][j-1];
}
}
int ans = 0;
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(grid[i][j] == 1){
int sum = 1;
for(int k=1;i+k<N&&j+k<M;k++){
if(Usum[i+k+1][j+1] - Usum[i+1][j+1] == k &&
Usum[i+k+1][j+k+1] - Usum[i+1][j+k+1] == k &&
Lsum[i+1][j+k+1] - Lsum[i+1][j+1] == k &&
Lsum[i+k+1][j+k+1] - Lsum[i+k+1][j+1] == k){
sum = max(sum, (k+1)*(k+1));
}
}
ans = max(ans, sum);
}
}
}
return ans;
}
};
// @lc code=end