Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:
i - k <= r <= i + k,
j - k <= c <= j + k, and
(r, c) is a valid position in the matrix.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[12,21,16],[27,45,33],[24,39,28]]
Example 2:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
Output: [[45,45,45],[45,45,45],[45,45,45]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n, k <= 100
1 <= mat[i][j] <= 100
解法1:presums 2D array
class Solution {
public:
vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
int nRow = mat.size();
if (nRow == 0) return presums;
int nCol = mat[0].size();
presums.resize(nRow + 1, vector<int>(nCol + 1, 0));
for (int i = 1; i <= nRow; i++) presums[i][1] = presums[i - 1][1] + mat[i - 1][0];
for (int i = 1; i <= nCol; i++) presums[1][i] = presums[1][i - 1] + mat[0][i - 1];
for (int i = 1; i <= nRow; i++) {
for (int j = 1; j <= nCol; j++) {
presums[i][j] = presums[i - 1][j] + presums[i][j - 1] - presums[i - 1][j - 1] + mat[i - 1][j - 1];
}
}
vector<vector<int>> res(nRow, vector<int>(nCol, 0));
for (int i = 0; i < nRow; i++) {
for (int j = 0; j < nCol; j++) {
int row1 = i - k + 1, row2 = i + k + 1;
int col1 = j - k + 1, col2 = j + k + 1;
if (row1 < 1) row1 = 1;
if (col1 < 1) col1 = 1;
if (row2 > nRow) row2 = nRow;
if (col2 > nCol) col2 = nCol;
res[i][j] = presums[row2][col2] - presums[row1 - 1][col2] - presums[row2][col1 - 1] + presums[row1 - 1][col1 - 1];
}
}
return res;
}
private:
vector<vector<int>> presums;
};