LC 1504. Count Submatrices With All Ones
link
Solution1:
class Solution {
public:
int m;
int n;
int numSubmat(vector<vector<int>>& mat) {
m=mat.size();
n=mat[0].size();
int res=0;
for(int up=0;up<m;up++){
vector<int> allone(n,1);
for(int down=up;down<m;down++){
for(int i=0;i<n;i++){
allone[i]&=mat[down][i];
}
res+=getcnt(allone);
}
}
return res;
}
int getcnt(vector<int>& allone){
int res=0;
int len=0;
for(int i=0;i<n;i++){
len=allone[i]==0?0:len+1;
res+=len;
}
return res;
}
};
Solution2:
class Solution {
public:
int m;
int n;
int numSubmat(vector<vector<int>>& mat) {
m=mat.size();
n=mat[0].size();
vector<int> col(n);
int res=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
col[j]=mat[i][j]==0?0 :col[j]+1;
}
res+=getcnt(col);
}
return res;
}
int getcnt(vector<int>& col){
stack<int> stk;
vector<int> cnt(n);
int res=0;
for(int i=0;i<n;i++){
while(!stk.empty() && col[i]<=col[stk.top()]) stk.pop();
if(stk.empty()){
cnt[i]=(i+1)*col[i];
res+=cnt[i];
}else{
cnt[i]=cnt[stk.top()]+(i-stk.top())*col[i];
res+=cnt[i];
}
stk.push(i);
}
return res;
}
};