nikunjsoni

304

May 12th, 2021
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. class NumMatrix {
  2. public:
  3.     int n, m;
  4.     vector<vector<int>> data;
  5.     NumMatrix(vector<vector<int>>& matrix) {
  6.         n = matrix.size();
  7.         m = matrix[0].size();
  8.        
  9.         for(int i=0; i<n; i++)
  10.             for(int j=1; j<m; j++){
  11.                 matrix[i][j] += matrix[i][j-1];
  12.             }
  13.         for(int i=0; i<m; i++)
  14.             for(int j=1; j<n; j++){
  15.                 matrix[j][i] += matrix[j-1][i];
  16.             }
  17.         data = matrix;
  18.     }
  19.    
  20.     int sumRegion(int row1, int col1, int row2, int col2) {
  21.         int ans = data[row2][col2];
  22.         if(row1 > 0) ans -= data[row1-1][col2];
  23.         if(col1 > 0) ans -= data[row2][col1-1];
  24.         if(row1 > 0 & col1 > 0) ans += data[row1-1][col1-1];
  25.         return ans;
  26.     }
  27. };
  28.  
  29. /**
  30.  * Your NumMatrix object will be instantiated and called as such:
  31.  * NumMatrix* obj = new NumMatrix(matrix);
  32.  * int param_1 = obj->sumRegion(row1,col1,row2,col2);
  33.  */
Advertisement
Add Comment
Please, Sign In to add comment