Skip to content

Commit 26aceb8

Browse files
committed
create 0304-range-sum-query-2d-immutable.cpp
1 parent fd2ee00 commit 26aceb8

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Diff for: cpp/0304-range-sum-query-2d-immutable.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class NumMatrix {
2+
public:
3+
4+
vector<vector<int>> dp;
5+
6+
NumMatrix(vector<vector<int>>& matrix) {
7+
int r = matrix.size(),c = matrix[0].size();
8+
dp = matrix;
9+
10+
for(int i =0;i<r;i++){
11+
for(int j =0;j<c;j++){
12+
if(i>0) dp[i][j] += dp[i-1][j]; // add prev row
13+
if(j>0) dp[i][j] += dp[i][j-1]; // add prev col
14+
15+
// remove diagonal as it is added twice above
16+
if(i>0&&j>0) dp[i][j] -= dp[i-1][j-1];
17+
}
18+
}
19+
}
20+
21+
int sumRegion(int row1, int col1, int row2, int col2) {
22+
int answer = dp[row2][col2];
23+
24+
if(row1>0) answer -= dp[row1-1][col2]; // remove prev row on col1
25+
if(col1>0) answer -= dp[row2][col1-1]; // remo prev col on row2
26+
27+
// add prev diagonal as pre row and prev col both contains that value
28+
if(row1>0&&col1>0) answer += dp[row1-1][col1-1];
29+
return answer;
30+
}
31+
};
32+
33+
/**
34+
* Your NumMatrix object will be instantiated and called as such:
35+
* NumMatrix* obj = new NumMatrix(matrix);
36+
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
37+
*/

0 commit comments

Comments
 (0)