1314. Matrix Block Sum

https://leetcode.com/problems/matrix-block-sum/

Given a m * 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

算法思路:

  • How to calculate the required sum for a cell (i,j) fast ?
  • Use the concept of cumulative sum array.
  • Create a cumulative sum matrix where dp[i][j] is the sum of all cells in the rectangle from (0,0) to (i,j), use inclusion-exclusion idea.
//O(nm)  O(nm)
class Solution {
public:
    vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int K) {
        int m = mat.size();
        int n = mat[0].size();
        
        for(int j = 1; j < n; j++) mat[0][j] = mat[0][j] + mat[0][j - 1];
        
        for(int i = 1; i < m; i++) mat[i][0] = mat[i][0] + mat[i - 1][0];
        
        for(int i = 1; i < m; i++) {
            for(int j = 1; j < n; j++) mat[i][j] += mat[i - 1][j] + mat[i][j - 1] - mat[i - 1][j - 1];
        }
        
        vector<vector<int>> ans(m, vector<int>(n, 0));
        int top, down, left, right;
        for(int i = 0; i < m; i++) {
            top = i - K - 1;
            down = min(m - 1, i + K);
            for(int j = 0; j < n; j++) {
                left = j - K - 1;
                right = min(n - 1, j + K);
                if(top < 0 && left < 0) ans[i][j] = mat[down][right];
                else if(top < 0) ans[i][j] = mat[down][right] - mat[down][left];
                else if(left < 0) ans[i][j] = mat[down][right] - mat[top][right];
                else ans[i][j] = mat[down][right] - mat[down][left] -mat[top][right] + mat[top][left];
            }
        }
        
        return ans;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值