题目链接:
力扣https://leetcode-cn.com/problems/image-smoother/
【分析】对于i,j处的格子,计算[i - 1, i + 1],[j - 1, j + 1]范围内的和以及元素个数即可,需要注意处理边界。
class Solution {
public int[][] imageSmoother(int[][] img) {
int m = img.length;
int n = img[0].length;
int[][] ans = new int[m][n];
int i, j, x1, y1, x2, y2, p, q, sum, num;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
x1 = i - 1; if(x1 < 0) x1 = 0;
y1 = j - 1; if(y1 < 0) y1 = 0;
x2 = i + 1; if(x2 >= m) x2 = m - 1;
y2 = j + 1; if(y2 >= n) y2 = n - 1;
sum = 0; num = 0;
for(p = x1; p <= x2; p++){
for(q = y1; q <= y2; q++){
sum += img[p][q]; num++;
}
}
ans[i][j] = sum / num;
}
}
return ans;
}
}
【方法二】前缀和,占个位置,后面补充。