原题链接

二维前缀和,置顶的模板里有
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];
}
};