Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Copy 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
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10
Copy // Binary Index Tree
class NumMatrix {
public:
NumMatrix(vector<vector<int>> matrix) { // time: O(mn*log(mn)); space: O(mn)
if (matrix.empty() || matrix[0].empty()) return;
int m = matrix.size(), n = matrix[0].size();
BIT = vector<vector<int> >(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
update(i, j, matrix[i][j]);
}
}
}
void update(int row, int col, int val) { // time: O(log(mn))
int orig = getSum(row + 1, col + 1) - getSum(row, col + 1) - getSum(row + 1, col) + getSum(row, col);
int diff = val - orig;
for (int i = row + 1; i < BIT.size(); i += (i & -i)) {
for (int j = col + 1; j < BIT[0].size(); j += (j & -j)) {
BIT[i][j] += diff;
}
}
}
int getSum(int row, int col) { // time: O(log(mn))
int sum = 0;
for (int i = row; i > 0; i -= (i & -i)) {
for (int j = col; j > 0; j -= (j & -j)) {
sum += BIT[i][j];
}
}
return sum;
}
int sumRegion(int row1, int col1, int row2, int col2) {
return getSum(row2 + 1, col2 + 1) - getSum(row1, col2 + 1) - getSum(row2 + 1, col1) + getSum(row1, col1);
}
vector<vector<int> > BIT;
};