Skip to content

Commit 1fc3ba8

Browse files
30.Range Sum Query 2D - Immutable
1 parent 64632a2 commit 1fc3ba8

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

30.Range Sum Query 2D - Immutable.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
2+
// Problem Description: https://leetcode.com/problems/range-sum-query-2d-immutable/
3+
4+
class NumMatrix {
5+
vector<vector<int>> ans;
6+
public:
7+
NumMatrix(vector<vector<int>>& matrix) {
8+
int prefix = 0;
9+
int above;
10+
int n = matrix.size(), m = matrix[0].size();
11+
ans.resize(n + 1, vector<int>(m + 1, 0));
12+
for (int r = 0; r < n; r++)
13+
{
14+
prefix = 0;
15+
for (int c = 0; c < m; c++)
16+
{
17+
prefix += matrix[r][c];
18+
above = ans[r][c + 1];
19+
ans[r + 1][c + 1] = prefix + above;
20+
}
21+
}
22+
}
23+
24+
int sumRegion(int row1, int col1, int row2, int col2) {
25+
row1++;
26+
row2++;
27+
col1++;
28+
col2++;
29+
int left, botright, above, leftabove;
30+
botright = ans[row2][col2];
31+
left = ans[row2][col1 - 1];
32+
above = ans[row1 - 1][col2];
33+
leftabove = ans[row1 - 1][col1 - 1];
34+
return botright - above - left + leftabove;
35+
}
36+
};
37+
38+
/**
39+
* Your NumMatrix object will be instantiated and called as such:
40+
* NumMatrix* obj = new NumMatrix(matrix);
41+
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
42+
*/

0 commit comments

Comments
 (0)