class NumMatrix {
public:
vector<vector<int>> sum;
NumMatrix(vector<vector<int>> matrix) {
int c=matrix.size();
if(matrix.empty())//先判断不为空,才能用matrix[0]
return ;
int r=matrix[0].size();
sum=vector<vector<int>>(c,vector<int>(r));
for(int i=0;i<c;i++)
{
for(int j=0;j<r;j++)
{
if(i==0&&j==0)
sum[i][j]=matrix[0][0];
else if(i==0)
sum[i][j]=sum[i][j-1]+matrix[i][j];
else if(j==0)
sum[i][j]=sum[i-1][j]+matrix[i][j];
else
sum[i][j]=sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+matrix[i][j];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
if(row1==0&&col1==0)
return sum[row2][col2];
else if(row1==0)
return sum[row2][col2]-sum[row2][col1-1];
else if(col1==0)
return sum[row2][col2]-sum[row1-1][col2];
else
return sum[row2][col2]-sum[row2][col1-1]-sum[row1-1][col2]+sum[row1-1][col1-1];
}
};
public:
vector<vector<int>> sum;
NumMatrix(vector<vector<int>> matrix) {
int c=matrix.size();
if(matrix.empty())//先判断不为空,才能用matrix[0]
return ;
int r=matrix[0].size();
sum=vector<vector<int>>(c,vector<int>(r));
for(int i=0;i<c;i++)
{
for(int j=0;j<r;j++)
{
if(i==0&&j==0)
sum[i][j]=matrix[0][0];
else if(i==0)
sum[i][j]=sum[i][j-1]+matrix[i][j];
else if(j==0)
sum[i][j]=sum[i-1][j]+matrix[i][j];
else
sum[i][j]=sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+matrix[i][j];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
if(row1==0&&col1==0)
return sum[row2][col2];
else if(row1==0)
return sum[row2][col2]-sum[row2][col1-1];
else if(col1==0)
return sum[row2][col2]-sum[row1-1][col2];
else
return sum[row2][col2]-sum[row2][col1-1]-sum[row1-1][col2]+sum[row1-1][col1-1];
}
};