Given a two-dimensional matrix, calculate the sum of the elements in its sub-rectangular range. The upper left corner of the sub-matrix is (row1, col1) and the lower right corner is (row2, col2).
Example:
Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12
analysis:
Similar to Question 303, a two-dimensional array is used to store the prefix sum of each row. Each element (ij) of the two-dimensional array represents the sum of the first j elements of the i-th row.
ps: The resize function can only define one dimension at a time. If it is a two-dimensional array, you need to resize the number of rows and then resize the number of columns to a certain row.
class NumMatrix {
public:
vector<vector<int>> mapSum;
NumMatrix(vector<vector<int>>& matrix) {
if(matrix.size() == 0 || matrix[0].size() == 0) return;
int m = matrix.size();
int n = matrix[0].size();
mapSum.resize(m);
for(int i = 0; i < m; i++){
mapSum[i].resize(n + 1, 0);
for(int j = 0; j < n; j++){
// 记录每一个行的前缀和
mapSum[i][j + 1] = mapSum[i][j] + matrix[i][j];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
int ret = 0;
// 计算每一行的区间和,累加即为选中矩阵的区域和
for(int i = row1; i <= row2; i++){
int temp = mapSum[i][col2 + 1] - mapSum[i][col1];
ret += temp;
}
return ret;
}
};