304.Range Sum Query 2D - Immutable

Given a 2D matrixmatrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1,col1) and lower right corner (row2,col2).


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

Example:

Method 1 O(1) time for lookup, O(mn) time for initialization, O(mn) space.:

  1. Set up a 2d array dp[rows+1][cols+1], needs additional blank row and column to remove edge case checking.
  2. Then we have dp[i+1][j+1] represents to sum of area from matrix[0][0] to matrix[i][j].
  3. Then we can have the following formula: sums[i][j] = sums[i-1][j] + sums[i][j-1] - sums[i-1][j-1] + matrix[i-1][j-1]
  4. Then finding the resulting sum of a specific area becomes simple.
 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
class NumMatrix(object):

    def __init__(self, matrix):
        if not matrix:
            return
        m,n = len(matrix)+1, len(matrix[0])+1
        self.dp = [[0] * n for _ in xrange(m)]
        for i in xrange(1, m):
            for j in xrange(1, n):
                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[row2+1][col1] - self.dp[row1][col2+1] + self.dp[row1][col1]

results matching ""

    No results matching ""