[leetcode] Two-dimensional area sum retrieval - matrix immutable (two-dimensional prefix sum)

Given a 2D matrix, calculate the sum of the elements in its subrectangle with the upper left corner of the submatrix as (row1, col1) and the lower right corner as (row2, col2).

The upper left corner of the submatrix in the above figure (row1, col1) = (2, 1) and the lower right corner (row2, col2) = (4, 3), and the sum of the elements in the sub-rectangle is 8.

Example:

Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12
说明:

You can assume the matrix is ​​immutable.
The sumRegion method is called multiple times.
You can assume row1 ≤ row2 and col1 ≤ col2.

Link: https://leetcode-cn.com/problems/range-sum-query-2d-immutable

Thought analysis:

This question is a two-dimensional prefix sum template question. If a two-dimensional area sum is required, the two-dimensional prefix sum can be preset first, and then the inclusion-exclusion theorem can be used to solve it.
The official solution is here

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

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix* obj = new NumMatrix(matrix);
 * int param_1 = obj->sumRegion(row1,col1,row2,col2);
 */

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325763661&siteId=291194637