1.题目要求:
给你一个 m x 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
2.题目代码:
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** matrixBlockSum(int** mat, int matSize, int* matColSize, int k, int* returnSize, int** returnColumnSizes) {
int** number = (int**)malloc(sizeof(int*) * matSize);
for(int i = 0;i < matSize;i++){
number[i] = (int*)malloc(sizeof(int) * (*matColSize));
}
for(int i = 0;i < matSize;i++){
for(int j = 0;j < *matColSize;j++){
int r1 = i - k;
int r2 = i + k;
int c1 = j - k;
int c2 = j + k;
while(r1 < 0){
r1++;
}
while(r2 > matSize - 1){
r2--;
}
while(c1 < 0){
c1++;
}
while(c2 > (*matColSize - 1))
{
c2--;
}
int sum = 0;
for(int i1 = r1;i1 <= r2;i1++){
for(int j1 = c1;j1 <= c2;j1++){
sum += mat[i1][j1];
}
}
number[i][j] = sum;
}
}
*returnSize = matSize;
*returnColumnSizes = (int*)malloc(sizeof(int) * (matSize));
for(int i = 0;i < matSize;i++){
(*returnColumnSizes)[i] = *matColSize;
}
return number;
}