Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. class NumMatrix {
  2.  
  3. int sum[][];
  4. int m;
  5. int n;
  6. public NumMatrix(int[][] matrix) {
  7. m = matrix.length;
  8. if(m ==0)
  9. return;
  10. n = matrix[0].length;
  11. sum = new int[m][n];
  12. for(int i =0;i<n;i++)
  13. {
  14. sum[0][i] = matrix[0][i];
  15. }
  16.  
  17. //Now do column wise sum
  18.  
  19. for(int i =1;i<m;i++)
  20. {
  21. for(int j =0;j<n;j++)
  22. {
  23. sum[i][j] = matrix[i][j] + sum[i-1][j];
  24. }
  25. }
  26.  
  27. //Now do row wise sum
  28. for(int i =0;i<m;i++)
  29. {
  30. for(int j =1;j<n;j++)
  31. {
  32. sum[i][j] = sum[i][j] + sum[i][j-1];
  33. }
  34. }
  35.  
  36. }
  37.  
  38. public int sumRegion(int row1, int col1, int row2, int col2) {
  39. if(row1>0 && col1>0)
  40. return sum[row2][col2] - sum[row1-1][col2] - sum[row2][col1-1] + sum[row1-1][col1-1];
  41. else if(row1==0 && col1>0)
  42. {
  43. return sum[row2][col2] - sum[row2][col1-1];
  44. }
  45. else if(row1>0 && col1==0)
  46. {
  47. return sum[row2][col2] - sum[row1-1][col2];
  48. }
  49. else{
  50. return sum[row2][col2];
  51. }
  52. }
  53. }
  54.  
  55. /**
  56. * Your NumMatrix object will be instantiated and called as such:
  57. * NumMatrix obj = new NumMatrix(matrix);
  58. * int param_1 = obj.sumRegion(row1,col1,row2,col2);
  59. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement