当前位置: 代码迷 >> 综合 >> Leetcode 1314. 矩阵区域和 转化二维前缀和
  详细解决方案

Leetcode 1314. 矩阵区域和 转化二维前缀和

热度:83   发布时间:2024-02-20 13:22:55.0

这道题目要可以确定边界,然后巧妙转化为二维前缀和问题, 注意边界的特殊处理。时间复杂度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;}
};