Leetcode 1314. Matrix Block Sum (2维前缀和数组)

  1. Matrix Block Sum
    Medium

Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:

i - k <= r <= i + k,
j - k <= c <= j + k, and
(r, c) is a valid position in the matrix.

Example 1:

Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[12,21,16],[27,45,33],[24,39,28]]
Example 2:

Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
Output: [[45,45,45],[45,45,45],[45,45,45]]

Constraints:

m == mat.length
n == mat[i].length
1 <= m, n, k <= 100
1 <= mat[i][j] <= 100

解法1:presums 2D array

class Solution {
public:
    vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
        int nRow = mat.size();
        if (nRow == 0) return presums;
        int nCol = mat[0].size();
        presums.resize(nRow + 1, vector<int>(nCol + 1, 0));
        for (int i = 1; i <= nRow; i++) presums[i][1] = presums[i - 1][1] + mat[i - 1][0];
        for (int i = 1; i <= nCol; i++) presums[1][i] = presums[1][i - 1] + mat[0][i - 1];
        for (int i = 1; i <= nRow; i++) {
            for (int j = 1; j <= nCol; j++) {
                presums[i][j] = presums[i - 1][j] + presums[i][j - 1] - presums[i - 1][j - 1] + mat[i - 1][j - 1];
            }
        }
        vector<vector<int>> res(nRow, vector<int>(nCol, 0));
        for (int i = 0; i < nRow; i++) {
            for (int j = 0; j < nCol; j++) {
                int row1 = i - k + 1, row2 = i + k + 1;
                int col1 = j - k + 1, col2 = j + k + 1;
                if (row1 < 1) row1 = 1;
                if (col1 < 1) col1 = 1;
                if (row2 > nRow) row2 = nRow;
                if (col2 > nCol) col2 = nCol;
                res[i][j] = presums[row2][col2] - presums[row1 - 1][col2] - presums[row2][col1 - 1] + presums[row1 - 1][col1 - 1];
            }
        }
        return res;
    }
private:
    vector<vector<int>> presums;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值