[Likou] 304. Two-dimensional area sum retrieval - Matrix immutable <two-dimensional prefix sum>

[Likou] 304. Two-dimensional area and retrieval-matrix immutable

Given a 2D matrix matrix, multiple requests of the following types:

  • Calculate the sum of the elements within its subrectangle, the upper left corner of this submatrix is (row1, col1)​​, and the lower right corner is (row2, col2).

Implementation NumMatrixclass:

  • NumMatrix(int[][] matrix)matrixInitialize given a matrix of integers
  • int sumRegion(int row1, int col1, int row2, int col2)Returns the sum of the elements of the submatrix described by the upper left corner (row1, col1)and lower right corner .(row2, col2)

Insert image description here

提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
- 1 0 5 10^5 105 <= matrix[i][j] <= 1 0 5 10^5 105
0 <= row1 <= row2 < m
0 <= col1 <= col2 < n
calls up to1 0 4 10^4104 times sumRegion method

Two-Dimensional Prefix Sum Theory

initialization

Insert image description here
Insert image description here
Hence the 2D prefix and preprocessing formula:

s[i][j] = s[i-1][j] + s[i][j-1] -s[i-1][j-1] + a[i][j]

Calculate area

Insert image description here
Insert image description here
Therefore, the two-dimensional prefix sum calculation formula is: (taking (x1, y1) as the upper left corner and (x2, y2) as the sum of the submatrices in the lower right corner)

s[x2][y2] - s[x2][y1 - 1] + s[x1 - 1][y2] -s[x1 - 1][y1 - 1]

answer

All plus one, the array starts from (0,0)

class NumMatrix {
    
    
    int[][] s;

    public NumMatrix(int[][] matrix) {
    
    
        int m = matrix.length;

        if (m > 0) {
    
    
            int n = matrix[0].length;
            s = new int[m + 1][n + 1];
            // 初始化
            for (int i = 0; i < m; i++) {
    
    
                for (int j = 0; j < n; j++) {
    
    
                    s[i + 1][j + 1] = s[i][j + 1] + s[i + 1][j] - s[i][j] + matrix[i][j];
                }
            }
        }
    }

	// 计算面积
    public int sumRegion(int x1, int y1, int x2, int y2) {
    
    
        return s[x2 + 1][y2 + 1] - s[x2 + 1][y1] - s[x1][y2 + 1]  + s[x1][y1];
    }
}

Guess you like

Origin blog.csdn.net/qq_44033208/article/details/132664714