leetcode5144. 矩陣區域和

給你一個 m * n 的矩陣 mat 和一個整數 K ,請你返回一個矩陣 answer ,其中每個 answer[i][j] 是所有滿足下述條件的元素 mat[r][c] 的和: 

i - K <= r <= i + K, j - K <= c <= j + K 
(r, c) 在矩陣內。
 

示例 1:

輸入:mat = [[1,2,3],[4,5,6],[7,8,9]], K = 1
輸出:[[12,21,16],[27,45,33],[24,39,28]]
示例 2:

輸入:mat = [[1,2,3],[4,5,6],[7,8,9]], K = 2
輸出:[[45,45,45],[45,45,45],[45,45,45]]
 

提示:

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

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/matrix-block-sum
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

 

class Solution {
public:
    vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int K) {
        int sum[110][110];
        int n = mat.size(), m = mat[0].size();
        memset(sum, 0, 0);
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= m; j++)
                sum[i][j] = mat[i - 1][j - 1] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][ j - 1 ];
        
        vector<vector<int>> ret(n, vector<int>(m));
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
            {
                int a = i + 1, b = j + 1;
                int x4 = min(a + K, n), y4 = min(b + K, m);
                int x1 = max(0, a - K - 1), y1 = max(0, b - K - 1);
                int x2 = max(0, a - K - 1), y2 = min(b + K, m);
                int x3 = min(n, a + K), y3 = max(0, b - K - 1);
                ret[i][j] = sum[x4][y4] - sum[x2][y2] - sum[x3][y3] + sum[x1][y1];
            }
        return ret;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章