class NumMatrix {
int m;
int n;
int[][] preSum;
public NumMatrix(int[][] matrix) {
m = matrix.length;
n = matrix[0].length;
preSum = new int[m][n];
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
int left = inArea(i,j-1) == true ? preSum[i][j-1]:0;
int up = inArea(i-1,j) == true ? preSum[i-1][j]:0;
int leftup = inArea(i-1,j-1) == true ? preSum[i-1][j-1]:0;
preSum[i][j] = left + up - leftup + matrix[i][j];
}
}
}
public boolean inArea(int x,int y){
return x >= 0 && x < m && y >= 0 && y < n;
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int left = inArea(row2,col1-1) == true ? preSum[row2][col1-1]:0;
int up = inArea(row1-1,col2) == true ? preSum[row1-1][col2]:0;
int leftup = inArea(row1-1,col1-1) == true ? preSum[row1-1][col1-1]:0;
return preSum[row2][col2] - left - up + leftup;
}
}