Share my C++ solution,easy to understand


  • 0
    V
    class NumMatrix {
    private:
        vector<vector<int>> sum_matrix;
        
    public:
        NumMatrix(vector<vector<int>> &matrix) {
            int row = matrix.size();
            if (row == 0)
                return;
            int col = matrix[0].size();
            if (col == 0)
                return;
            
            sum_matrix = vector<vector<int>>(row+1, vector<int>(col+1));
            
            //the first row
            for (int i = 0; i <= col; i++)
                sum_matrix[0][i] = 0;
            
            //the first col
            for (int i = 0; i <= row; i++)
                sum_matrix[i][0] = 0;
                
            for (int i = 1; i <= row; i++)
            {
                for (int j = 1; j <= col; j++)
                {
                    sum_matrix[i][j] = sum_matrix[i-1][j] + sum_matrix[i][j-1] - sum_matrix[i-1][j-1] + matrix[i-1][j-1];
                }
            }
        }
    
        int sumRegion(int row1, int col1, int row2, int col2) {
            int row = sum_matrix.size();
            if (row == 0)
                return 0;
        
            int col = sum_matrix[0].size();
            if (col == 0)
                return 0;
        
            row--;
            col--;
            if (row1 < 0 || row1 >= row || row2 < 0 || row2 >= row || col1 < 0 || col1 >= col || col2 < 0 || col2 >= col | row1 > row2 | col1 > col2)
                return 0;
            
            return sum_matrix[row2+1][col2+1] - sum_matrix[row1][col2+1] - sum_matrix[row2+1][col1] + sum_matrix[row1][col1];
        }
    };

Log in to reply
 

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