c++ easy clean solution


  • 0
    J

    in constructor, calculate the sum of area starting from position (0,0);

    class NumMatrix {
    private:
        vector<vector<int>> matrix;
    public:
        NumMatrix(vector<vector<int>> argument) {
            matrix = argument;
            int m=matrix.size();
            if(m == 0)
                return;
            int n=matrix[0].size();
            for(int i=0; i<m; i++)
            {
                for(int j=0; j<n; j++)
                {
                    matrix[i][j] += (i>0?matrix[i-1][j]:0) + (j>0?matrix[i][j-1]:0) - ((i>0 && j>0)?matrix[i-1][j-1]:0);
                }
            }
        }
        
        int sumRegion(int row1, int col1, int row2, int col2) {
           return matrix[row2][col2] - (row1>0?matrix[row1-1][col2]:0) - (col1>0?matrix[row2][col1-1]:0) + ((row1>0 && col1>0)?matrix[row1-1][col1-1]:0);
        }
    };
    

Log in to reply
 

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