https://leetcode.com/problems/matrix-block-sum/
Given a m * 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
算法思路:
- How to calculate the required sum for a cell (i,j) fast ?
- Use the concept of cumulative sum array.
- Create a cumulative sum matrix where dp[i][j] is the sum of all cells in the rectangle from (0,0) to (i,j), use inclusion-exclusion idea.
//O(nm) O(nm)
class Solution {
public:
vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int K) {
int m = mat.size();
int n = mat[0].size();
for(int j = 1; j < n; j++) mat[0][j] = mat[0][j] + mat[0][j - 1];
for(int i = 1; i < m; i++) mat[i][0] = mat[i][0] + mat[i - 1][0];
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) mat[i][j] += mat[i - 1][j] + mat[i][j - 1] - mat[i - 1][j - 1];
}
vector<vector<int>> ans(m, vector<int>(n, 0));
int top, down, left, right;
for(int i = 0; i < m; i++) {
top = i - K - 1;
down = min(m - 1, i + K);
for(int j = 0; j < n; j++) {
left = j - K - 1;
right = min(n - 1, j + K);
if(top < 0 && left < 0) ans[i][j] = mat[down][right];
else if(top < 0) ans[i][j] = mat[down][right] - mat[down][left];
else if(left < 0) ans[i][j] = mat[down][right] - mat[top][right];
else ans[i][j] = mat[down][right] - mat[down][left] -mat[top][right] + mat[top][left];
}
}
return ans;
}
};