# C# calculate sum first

• public class NumMatrix {

``````int[,] matrixSum;

public NumMatrix(int[,] matrix) {
int rows=matrix.GetLength(0);
int cols=matrix.GetLength(1);
if(rows==0)
{
matrixSum = new int[0,0];
return;
}
matrixSum = new int[rows,cols];
//caculate sum
matrixSum[0,0] = matrix[0,0];
for(int i=1; i<rows; i++)
{
matrixSum[i,0]=matrixSum[i-1,0]+matrix[i,0];
}
for(int j=1; j<cols; j++)
{
matrixSum[0,j]=matrixSum[0,j-1]+matrix[0,j];
}
for(int i=1;i<rows;i++)
{
for(int j=1;j<cols;j++)
{
matrixSum[i,j]=matrixSum[i,j-1]+matrixSum[i-1,j]+matrix[i,j]-matrixSum[i-1,j-1];
}
}
}

public int SumRegion(int row1, int col1, int row2, int col2) {
if(row1==0)
{
if(col1==0)
return matrixSum[row2,col2];
return matrixSum[row2,col2]-matrixSum[row2,col1-1];
}
else if(col1==0)
{
if(row1==0)
return matrixSum[row2,col2];
return matrixSum[row2,col2]-matrixSum[row1-1,col2];
}
else
return matrixSum[row2,col2]-matrixSum[row1-1,col2]-matrixSum[row2,col1-1]+matrixSum[row1-1,col1-1];
}
``````

}

// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix = new NumMatrix(matrix);
// numMatrix.SumRegion(0, 1, 2, 3);
// numMatrix.SumRegion(1, 2, 3, 4);

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