LeetCode304-二维区域和检索 - 矩阵不可变-二维前缀和-算法模板

原题链接
LeetCode304-二维区域和检索 - 矩阵不可变-二维前缀和-算法模板_第1张图片

二维前缀和,置顶的模板里有
class NumMatrix {
public:
    vector<vector<int>> g;

    NumMatrix(vector<vector<int>>& matrix) {
        int n = matrix.size(), m = matrix[0].size();
        g = vector<vector<int>>(n + 1, vector<int>(m + 1));
        for(int i = 0; i < n; i ++)
            for(int j = 0; j < m; j ++){
                int a = matrix[i][j], x = i + 1, y = j + 1;
                g[x][y] = g[x - 1][y] + g[x][y - 1] + a - g[x - 1][y - 1];
            }
    }
    
    int sumRegion(int x1, int y1, int x2, int y2) {
        x1 ++, y1 ++, x2 ++, y2 ++;
        return g[x2][y2] - g[x1 - 1][y2] - g[x2][y1 - 1] + g[x1 - 1][y1 - 1];
    }
};

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

你可能感兴趣的:(算法,矩阵,leetcode,前缀和,模板)