Title Description
Given a two-dimensional matrix, calculates the sum of its sub-rectangles range of elements, the upper left corner of the sub-matrix (row1, col1), the lower right corner (row2, col2).
FIG upper left corner submatrix sum (row1, col1) = (2 , 1), bottom right (row2, col2) = (4 , 3), within the sub-rectangle element 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
Thinking
Code
class NumMatrix:
def __init__(self,matrix):
m = len(matrix)
n = len(matrix[0])
self.dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
self.dp[i][j] = self.dp[i-1][j] + self.dp[i][j-1] + matrix[i-1][j-1] - self.dp[i-1][j-1]
def sumRegion(self,row1,col1,row2,col2):
return self.dp[row2+1][col2+1] - self.dp[row1][col2+1] - self.dp[row2+1][col1] + self.dp[row1][col1]
matrix = NumMatrix([
[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]
])
test = matrix.sumRegion(2, 1, 4, 3)
print(test)