Iam_Sandeep

302. 2D prefix sum

Jul 23rd, 2022
1,005
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. class NumMatrix:
  2.  
  3.     def __init__(self, m: List[List[int]]):
  4.         r,c=len(m),len(m[0])
  5.         self.dp=dp=[[0]*(c+1) for i in range(r+1)]
  6.         #final sum from (0,0) to (r,c) of matrix m stores at (r+1,c+1)
  7.        
  8.         #we will go with 0-index array only but update on dp
  9.         for i in range(r):
  10.             prefix=0 #current row prefix sum=0
  11.             for j in range(c):
  12.                 prefix+=m[i][j]  #add next element in the row
  13.                 above=dp[i][j+1] #add above (i+1,j+1) of dp table
  14.                 dp[i+1][j+1]=prefix+above
  15.                 #store at i+1 j+1
  16.        
  17.  
  18.     def sumRegion(self, r1: int, c1: int, r2: int, c2: int) -> int:
  19.         #sum1=dp[r1+1][c1+1]
  20.         #we will increment by 1 beacuase we are storing sums in 1 indexed array
  21.         r1,r2,c1,c2=r1+1,r2+1,c1+1,c2+1
  22.         dp=self.dp
  23.         corner=dp[r1-1][c1-1]
  24.         left=dp[r2][c1-1]
  25.         top=dp[r1-1][c2]
  26.         total=dp[r2][c2]
  27.         return total-left-top+corner
  28.     #we are substracting it because it is common part of left and top
  29.  
  30. # Your NumMatrix object will be instantiated and called as such:
  31. # obj = NumMatrix(matrix)
  32. # param_1 = obj.sumRegion(row1,col1,row2,col2)
Advertisement
Add Comment
Please, Sign In to add comment