Simple Python Solution

  • 0
    class NumMatrix(object):
        def __init__(self, matrix):
            self.matrix = matrix
            self.m = len(matrix)
            self.n = len(matrix[0]) if self.m else 0
            self.t = [[0]*(self.n+1) for _ in range(self.m)]
            for i in range(self.m):
                for j in range(self.n):
                    self.t[i][j+1] += self.t[i][j] + matrix[i][j]
        def update(self, row, col, val):
            d = val-self.matrix[row][col]
            self.matrix[row][col] = val
            for j in range(col,self.n):
                self.t[row][j+1] += d
        def sumRegion(self, row1, col1, row2, col2):
            ans = 0
            for i in range(row1, row2+1):
                ans += self.t[i][col2+1] - self.t[i][col1]
            return ans

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.