1. 程式人生 > 其它 >二維字首和模版(來自leetcode)

二維字首和模版(來自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) 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。