Untitled
unknown
plain_text
2 years ago
901 B
11
Indexable
class NumMatrix {
public:
vector<vector<int>>pre;
NumMatrix(vector<vector<int>>& mat) {
int r=mat.size(), c=mat[0].size();
pre.resize(r,vector<int>(c,0));
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
pre[i][j]=mat[i][j];
if(i>0) pre[i][j]+=pre[i-1][j];
if(j>0) pre[i][j]+=pre[i][j-1];
if(i>0 && j>0) pre[i][j]-=pre[i-1][j-1];
}
}
}
int sumRegion(int r1, int c1, int r2, int c2) {
int res=pre[r2][c2];
if(r1>0) res-=pre[r1-1][c2];
if(c1>0) res-=pre[r2][c1-1];
if(r1>0 && c1>0) res+=pre[r1-1][c1-1];
return res;
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
*/Editor is loading...
Leave a Comment