## # 304. Range Sum Query 2D - Immutable

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).

Range Sum Query 2D The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

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
``````

Note:

1. You may assume that the matrix does not change.
2. There are many calls to sumRegion function.
3. You may assume that row1 ≤ row2 and col1 ≤ col2.

### # Solution

Approach 1: Cache and then calculate in O(1).

### # Code (Python)

Approach 1:

``````class NumMatrix:

def __init__(self, matrix: List[List[int]]):
self.sums = [[0] * len(matrix[0]) for _ in range(len(matrix))]
if not self.sums:
return
self.sums[0][0] = matrix[0][0]
for i in range(1, len(matrix[0])):
self.sums[0][i] = self.sums[0][i-1] + matrix[0][i]
for j in range(1, len(matrix)):
self.sums[j][0] = self.sums[j-1][0] + matrix[j][0]
for j in range(1, len(matrix)):
for i in range(1, len(matrix[0])):
self.sums[j][i] = self.sums[j-1][i] + self.sums[j][i-1] - self.sums[j-1][i-1] + matrix[j][i]

def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
if row1 == 0 and col1 == 0:
return self.sums[row2][col2]
if row1 == 0:
return self.sums[row2][col2] - self.sums[row2][col1-1]
if col1 == 0:
return self.sums[row2][col2] - self.sums[row1-1][col2]
return self.sums[row2][col2] - (self.sums[row2][col1-1] + self.sums[row1-1][col2] - self.sums[row1-1][col1-1])

# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# param_1 = obj.sumRegion(row1,col1,row2,col2)
``````

### # Code (C++)

Approach 1:

``````class NumMatrix {
private:
vector<vector<int>> buf;
public:
NumMatrix(vector<vector<int>>& matrix) {
int m = matrix.size();
if (m == 0) return;
int n = matrix[0].size();
if (n == 0) return;
buf = vector<vector<int>>(m, vector<int>(n, 0));
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
buf[i][j] = matrix[i][j];
if (i > 0)
buf[i][j] += buf[i-1][j];
if (j > 0)
buf[i][j] += buf[i][j-1];
if (i > 0 && j > 0)
buf[i][j] -= buf[i-1][j-1];
}
}
}

int sumRegion(int row1, int col1, int row2, int col2) {
int res = buf[row2][col2];
if (row1 > 0)
res -= buf[row1-1][col2];
if (col1 > 0)
res -= buf[row2][col1-1];
if (row1 > 0 && col1 > 0)
res += buf[row1-1][col1-1];
return res;
}
};

/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
*/
``````