二维前缀和模版(来自leetcode)
//题号1314: 我自己的思路是用一维行前缀和写的,但二维前缀和的公式是有的:
//s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + mat[i - 1][j - 1];
//知道公式了,把边界问题处理了,就很好过了
class Solution { public: vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) { int n = mat.size(), m = mat[0].size(); 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]; //加mat[i - 1][j - 1]是为了方便计算,偏移一下 } } vector<vector<int>> res; for(int i = 1; i <= n; i++){ vector<int> tmp; for(int j = 1; j <= m; j++){ int x1 = i - k, y1 = j - k, x2 = i + k, y2 = j + k; if(x1 < 1)x1 = 1; //四个边界需要特殊判断一下 if(y1 < 1)y1 = 1; if(x2 > n)x2 = n; if(y2 > m)y2 = m; tmp.push_back(s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] + s[x1 - 1][y1 - 1]); } res.push_back(tmp); } return res; } }; 作者:NZAMF 链接:https://leetcode-cn.com/problems/matrix-block-sum/solution/qian-zhui-he-mo-ban-by-nzamf-ldfy/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。