1504. 统计全 1 子矩形
做法与力扣85题极为相似。
枚举+前缀和,前缀和来快速判断某一行是不是全为1。
class Solution {
public:
int numSubmat(vector<vector<int>>& a) {
vector<vector<int>> pre = a;
int ans = 0 , m = a.size(), n = a[0].size();
for(int i=0;i<m;i++){
for(int j=1;j<n;j++){
pre[i][j] += pre[i][j-1];
}
}
for(int l=0;l<n;l++){
for(int r=l;r<n;r++){
int now = 0;
for(int i=0;i<m;i++){
int s = pre[i][r];
if(l>0){
s -= pre[i][l-1];
}
if(s==r-l+1){
now++;
}else{
ans += (now+1)*now/2;
now = 0;
}
}
if(now>0){
ans += (now+1)*now/2;
}
}
}
return ans;
}
};