304. 二维区域和检索 - 矩阵不可变

  1. class NumMatrix {
  2. private int[][] matrix;
  3. private int rows;
  4. private int cols;
  5. public NumMatrix(int[][] matrix) {
  6. if (matrix == null)
  7. this.matrix = null;
  8. rows = matrix.length;
  9. if (rows > 0) {
  10. cols = matrix[0].length;
  11. this.matrix = new int[rows][cols];
  12. for (int i = 0; i < rows; i++)
  13. for (int j = 0; j < cols; j++)
  14. this.matrix[i][j] = matrix[i][j];
  15. }
  16. }
  17. public int sumRegion(int row1, int col1, int row2, int col2) {
  18. if (matrix == null || row2 > rows || col2 > cols)
  19. return 0;
  20. int sum = 0;
  21. for (int i = row1; i <= row2; i++)
  22. for (int j = col1; j <= col2; j++)
  23. sum += matrix[i][j];
  24. return sum;
  25. }
  26. }
  27. /**
  28. * Your NumMatrix object will be instantiated and called as such:
  29. * NumMatrix obj = new NumMatrix(matrix);
  30. * int param_1 = obj.sumRegion(row1,col1,row2,col2);
  31. */