-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path304.cpp
More file actions
68 lines (63 loc) · 1.82 KB
/
Copy path304.cpp
File metadata and controls
68 lines (63 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*******************************************************************************
> File Name: 304.cpp
> Author: sillyplus
> Mail: oi_boy@sina.cn
> Created Time: Wed Mar 23 11:29:53 2016
*******************************************************************************/
class NumMatrix {
private:
vector<vector<int>> rowSum;
vector<vector<int>> colRowSum;
int rn, ln;
public:
NumMatrix(vector<vector<int>> &matrix) {
rn = matrix.size();
if (rn == 0) return;
ln = matrix[0].size();
for (int i = 0; i < rn; ++i) {
vector<int> row = matrix[i];
vector<int> tmp;
int sum = 0;
for (int j = 0; j < ln; ++j) {
sum += row[j];
tmp.push_back(sum);
}
rowSum.push_back(tmp);
}
for (int i = 0; i < ln; ++i) {
int sum = 0;
vector<int> tmp;
for (int j = 0; j < rn; ++j) {
sum += rowSum[j][i];
tmp.push_back(sum);
}
colRowSum.push_back(tmp);
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
int ret;
int rt1, rt2, rt3, rt4;
rt1 = colRowSum[col2][row2];
if (row1 == 0) {
rt2 = 0;
} else {
rt2 = colRowSum[col2][row1-1];
}
if (col1 == 0) {
rt3 = 0;
} else {
rt3 = colRowSum[col1-1][row2];
}
if (row1 == 0 || col1 == 0) {
rt4 = 0;
} else {
rt4 = colRowSum[col1-1][row1-1];
}
ret = rt1 - rt2 - rt3 + rt4;
return ret;
}
};
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);