problem
1314. Matrix Block Sum
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]]
wrong approach 1 TLE
class Solution {
public:
vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
int m = mat.size(), n = mat[0].size();
vector<vector<int>> ans(m, vector<int>(n, 0));
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
for(int r=max(i-k, 0); r<=min(i+k, m-1); r++)
for(int c=max(j-k, 0); c<=min(j+k, n-1); c++)
ans[i][j] += mat[r][c];
}
}
return ans;
}
};
approach 2 DP
class Solution {
public:
vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
int m = mat.size(), n = mat[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
for(int r=0; r<=min(k, m-1); r++)
for(int c=0; c<=min(k, n-1); c++)
dp[0][0] += mat[r][c];
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(i==0 && j==0) continue;
if(j==0){// down
dp[i][j] += dp[i-1][j];
if(i-1-k >= 0){//del
for(int c=max(j-k, 0); c<=min(j+k, n-1); c++)
dp[i][j] -= mat[i-1-k][c];
}
if(i+k < m){// add
for(int c=max(j-k, 0); c<=min(j+k, n-1); c++)
dp[i][j] += mat[i+k][c];
}
}else{//right
dp[i][j] += dp[i][j-1];
if(j-1-k >= 0){// del
for(int r=max(i-k, 0); r<=min(i+k, m-1); r++)
dp[i][j] -= mat[r][j-1-k];
}
if(j+k < n){// add
for(int r=max(i-k, 0); r<=min(i+k, m-1); r++)
dp[i][j] += mat[r][j+k];
}
}
}
}
return dp;
}
};
approach 3 wonderful DP
class Solution {
public:
int m,n;
vector<vector<int>> prefix;
int get(int i, int j){
if(i<0 || j<0) return 0;
if(i >= m) i=m-1;
if(j >= n) j=n-1;
return prefix[i][j];
}
vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
m = mat.size(), n = mat[0].size();
prefix = vector<vector<int>>(m, vector<int>(n, 0));
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
prefix[i][j] = mat[i][j] + get(i-1, j) + get(i, j-1) - get(i-1, j-1);
vector<vector<int>> res = vector<vector<int>>(m, vector<int>(n, 0));
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
res[i][j] = get(i+k,j+k) + get(i-k-1, j-k-1) - get(i+k, j-k-1) - get(i-k-1, j+k);
return res;
}
};