这道题目要可以确定边界,然后巧妙转化为二维前缀和问题, 注意边界的特殊处理。时间复杂度O(n^2)
class Solution {
public:// 1 2 3// 4 5 6// 7 8 9vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int K) {int n = mat.size(), m = mat[0].size();vector<vector<int>> res(n,vector<int>(m));vector<vector<int>> s(n+1,vector<int>(m+1));for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){s[i][j] = s[i-1][j] + s[i][j-1] - s[i-1][j-1] + mat[i-1][j-1];}}for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){int x1 = max(0,i-K-1);int x2 = min(n,i+K);int y1 = max(0,j-K-1);int y2 = min(m,j+K);res[i-1][j-1] = s[x2][y2] - s[x1][y2] - s[x2][y1] + s[x1][y1];}}return res;}
};