classNumMatrix{public:NumMatrix(vector<vector<int>>&matrix){if(matrix.empty())return;constintm=matrix.size();constintn=matrix[0].size();// prefix[i][j] := sum of matrix[0..i)[0..j)prefix.resize(m+1,vector<int>(n+1));for(inti=0;i<m;++i)for(intj=0;j<n;++j)prefix[i+1][j+1]=matrix[i][j]+prefix[i][j+1]+prefix[i+1][j]-prefix[i][j];}intsumRegion(introw1,intcol1,introw2,intcol2){returnprefix[row2+1][col2+1]-prefix[row1][col2+1]-prefix[row2+1][col1]+prefix[row1][col1];}private:vector<vector<int>>prefix;};
classNumMatrix{publicNumMatrix(int[][]matrix){if(matrix.length==0)return;finalintm=matrix.length;finalintn=matrix[0].length;// prefix[i][j] := sum of matrix[0..i)[0..j)prefix=newint[m+1][n+1];for(inti=0;i<m;++i)for(intj=0;j<n;++j)prefix[i+1][j+1]=matrix[i][j]+prefix[i][j+1]+prefix[i+1][j]-prefix[i][j];}publicintsumRegion(introw1,intcol1,introw2,intcol2){returnprefix[row2+1][col2+1]-prefix[row1][col2+1]-prefix[row2+1][col1]+prefix[row1][col1];}privateint[][]prefix;}
classNumMatrix:def__init__(self,matrix:List[List[int]]):ifnotmatrix:returnm=len(matrix)n=len(matrix[0])# prefix[i][j] := sum of matrix[0..i)[0..j)self.prefix=[[0]*(n+1)for_inrange(m+1)]foriinrange(m):forjinrange(n):self.prefix[i+1][j+1]= \
matrix[i][j]+self.prefix[i][j+1]+ \
self.prefix[i+1][j]-self.prefix[i][j]defsumRegion(self,row1:int,col1:int,row2:int,col2:int)->int:returnself.prefix[row2+1][col2+1]-self.prefix[row1][col2+1]- \
self.prefix[row2+1][col1]+self.prefix[row1][col1]