LeetCode 1314. 矩阵区域和

1314. 矩阵区域和

 

 【二维前缀和】

class Solution {
    public int[][] matrixBlockSum(int[][] mat, int k) {
        int m = mat.length, n = mat[0].length;
        int[][] pre = new int[m + 1][n + 1];
        for(var i = 1; i <= m; i++){
            for(var j = 1; j <= n; j++){
                pre[i][j] = pre[i - 1][j] + pre[i][j - 1] + mat[i - 1][j - 1] - pre[i - 1][j - 1];
            }
        }
        int[][] ans = new int[m][n];
        for(var i = 0; i < m; i++){
            for(var j = 0; j < n; j++){
                int x1 = i + 1 - k; if(x1 < 1) x1 = 1;
                int y1 = j + 1 - k; if(y1 < 1) y1 = 1;
                int x2 = i + 1 + k; if(x2 > m) x2 = m;
                int y2 = j + 1 + k; if(y2 > n) y2 = n;
                ans[i][j] = pre[x2][y2] - pre[x2][y1 - 1] - pre[x1 - 1][y2] + pre[x1 - 1][y1 - 1];
            }
        }
        return ans;
    }
}

你可能感兴趣的:(LeetCode,leetcode,二维前缀和)